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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { CLIENT_ARCHIVE_ACTION } from '@/lib/auth/permissions';
import { parseBody } from '@/lib/api/route-helpers';
import { getClientArchiveDossier } from '@/lib/services/client-archive-dossier.service';
import { errorResponse } from '@/lib/errors';

const bodySchema = z.object({
  ids: z.array(z.string().min(1)).min(1).max(100),
});

interface PreflightItem {
  clientId: string;
  fullName: string;
  stakeLevel: 'low' | 'high';
  highStakesStage: string | null;
  blockers: string[];
  summary: { berths: number; yachts: number; tenancies: number; signedDocs: number };
}

/**
 * Preflight check for the bulk-archive wizard. Returns the per-client
 * stake level + a small summary so the UI can:
 *   - count how many will auto-archive
 *   - cycle through high-stakes clients to capture per-client reasons
 *   - surface blockers (e.g. "has unpaid invoices") for the operator
 */
export const POST = withAuth(
  withPermission('clients', CLIENT_ARCHIVE_ACTION, async (req, ctx) => {
    try {
      const { ids } = await parseBody(req, bodySchema);
      const items: PreflightItem[] = [];
      for (const id of ids) {
        try {
          const d = await getClientArchiveDossier(id, ctx.portId);
          items.push({
            clientId: d.client.id,
            fullName: d.client.fullName,
            stakeLevel: d.stakeLevel,
            highStakesStage: d.highStakesStage,
            blockers: d.blockers,
            summary: {
              berths: d.berths.length,
              yachts: d.yachts.length,
              tenancies: d.tenancies.length,
              signedDocs: d.documents.filter(
                (doc) => doc.status === 'completed' || doc.status === 'signed',
              ).length,
            },
          });
        } catch {
          // Generic blocker text - never include the inner error so an
          // attacker can't distinguish "not found" from "in another port"
          // by enumerating UUIDs (audit R2-M9). The operator already
          // selected these IDs so they don't need to know the cause.
          items.push({
            clientId: id,
            fullName: '(unknown)',
            stakeLevel: 'low',
            highStakesStage: null,
            blockers: ['Could not load dossier - client may have been removed'],
            summary: { berths: 0, yachts: 0, tenancies: 0, signedDocs: 0 },
          });
        }
      }
      return NextResponse.json({ data: items });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
