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 } from '@/lib/errors';
import { updateExternalEoiMetadata } from '@/lib/services/external-eoi.service';

const signatorySchema = z.object({
  id: z.string().uuid().optional(),
  name: z.string().min(1).max(200),
  email: z.string().email(),
  role: z.enum(['client', 'developer', 'rep', 'witness', 'cc']),
});

const patchSchema = z
  .object({
    title: z.string().min(1).max(500).optional(),
    signedAt: z
      .string()
      .datetime({ offset: true })
      .or(z.string().regex(/^\d{4}-\d{2}-\d{2}$/))
      .nullable()
      .optional(),
    notes: z.string().max(4000).optional(),
    signatories: z.array(signatorySchema).max(20).optional(),
  })
  .strict()
  .refine(
    (v) =>
      v.title !== undefined ||
      v.signedAt !== undefined ||
      v.notes !== undefined ||
      v.signatories !== undefined,
    { message: 'At least one field must be provided' },
  );

/**
 * PATCH /api/v1/documents/[id]/metadata
 *
 * Edits title / signed-date / notes / signatories on a previously-uploaded
 * external (manually-uploaded) document. Service throws ConflictError for
 * Documenso-managed docs (vendor owns their signers) and for non-EOI
 * document types (form shape isn't widened yet).
 */
export const PATCH = withAuth(
  withPermission('documents', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, patchSchema);
      const signedAtValue =
        body.signedAt === undefined
          ? undefined
          : body.signedAt === null
            ? null
            : new Date(body.signedAt);
      await updateExternalEoiMetadata({
        documentId: params.id!,
        portId: ctx.portId,
        title: body.title,
        signedAt: signedAtValue,
        notes: body.notes,
        signatories: body.signatories,
        meta: {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
