import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canManageHumanCapital, ensureEmployeeProfiles } from "@/lib/human-capital";

export async function GET() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canManageHumanCapital(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/HC leaders can view headcount." }, { status: 403 });
  }

  await ensureEmployeeProfiles();

  const profiles = await prisma.employeeProfile.findMany({
    where: { employmentStatus: "active" },
    include: {
      user: {
        select: {
          id: true,
          name: true,
          email: true,
          departmentRole: true,
        },
      },
    },
  });

  const byLocationRole = new Map<string, number>();
  for (const profile of profiles) {
    const locationCode = profile.locationId ?? "sin_ubicacion";
    const roleKey = profile.user.departmentRole ?? "sin_rol";
    const key = `${locationCode}::${roleKey}`;
    byLocationRole.set(key, (byLocationRole.get(key) ?? 0) + 1);
  }

  const breakdown = Array.from(byLocationRole.entries()).map(([key, count]) => {
    const [locationCode, roleKey] = key.split("::");
    return { locationCode, roleKey, count };
  });

  return NextResponse.json({
    ok: true,
    total: profiles.length,
    breakdown,
  });
}
