import { NextResponse } from 'next/server';
import { and, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { clients } from '@/lib/db/schema/clients';
import { errorResponse } from '@/lib/errors';

/**
 * GET /api/v1/dashboard/clients-by-country
 *
 * Returns a per-country breakdown of non-archived clients in the port,
 * keyed by ISO-3166-1 alpha-2 country code. Powers the "Clients by
 * country" dashboard widget.
 *
 * Skips rows with no nationality recorded. Sorted by count desc; ties
 * break alphabetically by country code so the widget stays stable
 * across refreshes.
 */
export const GET = withAuth(
  withPermission('clients', 'view', async (_req, ctx) => {
    try {
      const rows = await db
        .select({
          country: clients.nationalityIso,
          count: sql<number>`COUNT(*)::int`,
        })
        .from(clients)
        .where(
          and(
            eq(clients.portId, ctx.portId),
            isNull(clients.archivedAt),
            isNotNull(clients.nationalityIso),
          ),
        )
        .groupBy(clients.nationalityIso)
        .orderBy(desc(sql`COUNT(*)`), clients.nationalityIso);

      const total = rows.reduce((sum, r) => sum + Number(r.count ?? 0), 0);

      return NextResponse.json({
        data: rows.map((r) => ({
          country: r.country,
          count: Number(r.count ?? 0),
        })),
        total,
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
