import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getPortDocumensoConfig } from '@/lib/services/port-config';

/**
 * GET `/api/v1/documents/template-defaults`
 *
 * Returns the per-port default Documenso template id keyed by
 * documentType. The CreateDocumentWizard reads this to auto-resolve
 * the template the rep doesn't have to remember — picking "EOI" /
 * "Reservation Agreement" / "Contract" defaults to the matching port
 * template id. Admins with the explicit perm can still override via
 * the DocumentTemplatePicker.
 *
 * Permission: documents.create — the only caller is the wizard which
 * already requires this permission to complete the flow. View-only
 * roles don't see the wizard at all.
 *
 * Response:
 *   { data: { eoi: number | null, contract: number | null,
 *             reservation_agreement: number | null } }
 *
 * `null` means no template configured for that doc type (rep must
 * pick one manually via the override picker).
 */
export const GET = withAuth(
  withPermission('documents', 'create', async (_req, ctx) => {
    try {
      const cfg = await getPortDocumensoConfig(ctx.portId);
      return NextResponse.json({
        data: {
          eoi: cfg.eoiTemplateId > 0 ? cfg.eoiTemplateId : null,
          contract: cfg.contractTemplateId,
          reservation_agreement: cfg.reservationTemplateId,
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
