import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { generateAndSign } from '@/lib/services/document-templates';
import { generateAndSignSchema } from '@/lib/validators/document-templates';

export const POST = withAuth(
  withPermission('documents', 'create', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, generateAndSignSchema);
      const result = await generateAndSign(
        params.id === 'documenso-template' ? null : params.id!,
        ctx.portId,
        {
          clientId: body.clientId,
          interestId: body.interestId,
          berthId: body.berthId,
        },
        body.signers,
        body.pathway,
        {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
        {
          dimensionUnit: body.dimensionUnit,
          overrides: body.overrides,
          includeYachtDetails: body.includeYachtDetails,
        },
      );
      return NextResponse.json({ data: result }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
