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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { sendReminderIfAllowed } from '@/lib/services/document-reminders';

const remindBodySchema = z
  .object({
    signerId: z.string().optional(),
  })
  .optional();

export const POST = withAuth(
  withPermission('documents', 'edit', async (req, ctx, params) => {
    try {
      let signerId: string | undefined;
      const text = await req.text();
      if (text) {
        const parsed = remindBodySchema.safeParse(JSON.parse(text));
        if (parsed.success && parsed.data) signerId = parsed.data.signerId;
      }
      const result = await sendReminderIfAllowed(params.id!, ctx.portId, {
        auto: false,
        signerId,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
