import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { uploadSignedManually } from '@/lib/services/documents.service';

export const POST = withAuth(
  withPermission('documents', 'edit', async (req, ctx, params) => {
    try {
      const formData = await req.formData();
      const file = formData.get('file') as File | null;

      if (!file) {
        throw new ValidationError('No file provided');
      }

      const buffer = Buffer.from(await file.arrayBuffer());

      const doc = await uploadSignedManually(
        params.id!,
        ctx.portId,
        {
          buffer,
          originalName: file.name,
          mimeType: file.type || 'application/pdf',
          size: file.size,
        },
        {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      );

      return NextResponse.json({ data: doc });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
