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/signing-defaults`
 *
 * Returns the per-port developer + approver defaults the
 * UploadForSigningDialog uses to prefill the recipient configurator.
 * No secrets are exposed — just the display name, email, and the
 * sendMode flag so the UI can show the right CTA copy ("Send now" vs
 * "Save draft, send manually").
 *
 * Permission: documents.send_for_signing — the only caller is the
 * upload-for-signing dialog which already requires this permission to
 * complete the flow.
 */
export const GET = withAuth(
  withPermission('documents', 'send_for_signing', async (_req, ctx) => {
    try {
      const cfg = await getPortDocumensoConfig(ctx.portId);
      return NextResponse.json({
        data: {
          developer: {
            name: cfg.developerName ?? '',
            email: cfg.developerEmail ?? '',
            label: cfg.developerLabel ?? 'Developer',
          },
          approver: {
            name: cfg.approverName ?? '',
            email: cfg.approverEmail ?? '',
            label: cfg.approverLabel ?? 'Approver',
          },
          sendMode: cfg.sendMode,
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
