import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { markExternallySigned } from '@/lib/services/external-signing.service';

const bodySchema = z.object({
  docType: z.enum(['eoi', 'reservation', 'contract']),
  reason: z.string().trim().max(2000).optional(),
});

/**
 * POST /api/v1/interests/[id]/mark-externally-signed
 *
 * Marks the named document type as signed without requiring a file
 * upload. Sets the relevant `*_doc_status` column to 'signed', writes
 * an audit log entry capturing the reason, and fires the appropriate
 * berth-rule trigger (eoi_signed / contract_signed) if any.
 */
export const POST = withAuth(
  withPermission('interests', 'edit', async (req, ctx, params) => {
    try {
      const interestId = params.id;
      if (!interestId) throw new NotFoundError('Interest');
      const input = await parseBody(req, bodySchema);
      const result = await markExternallySigned(
        {
          interestId,
          portId: ctx.portId,
          docType: input.docType,
          reason: input.reason ?? null,
        },
        {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      );
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
