import { NextRequest, NextResponse } from 'next/server';
import { uploadDocumentLibraryVersion } from '@/features/foundation/document-library/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = { params: Promise<{ id: string }> };

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentLibraryUpload
    });

    const formData = await request.formData();
    const version = formData.get('version');
    const file = formData.get('file');

    if (typeof version !== 'string' || !version.trim()) {
      return NextResponse.json({ message: 'Version is required' }, { status: 400 });
    }

    if (!(file instanceof File)) {
      return NextResponse.json({ message: 'PDF file is required' }, { status: 400 });
    }

    const created = await uploadDocumentLibraryVersion({
      libraryId: id,
      organizationId: organization.id,
      userId: session.user.id,
      version,
      file: {
        name: file.name,
        type: file.type,
        size: file.size,
        buffer: Buffer.from(await file.arrayBuffer())
      }
    });

    return NextResponse.json({
      success: true,
      message: 'Document library version uploaded successfully',
      version: created
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json(
      { message: 'Unable to upload document library version' },
      { status: 500 }
    );
  }
}
