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

export async function GET(request: Request) {
  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 payroll summary." }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const runId = searchParams.get("runId");

  const run = runId
    ? await prisma.hrPayrollRun.findUnique({ where: { id: runId } })
    : await prisma.hrPayrollRun.findFirst({
        where: { department: "capital_humano" },
        orderBy: [{ periodEnd: "desc" }, { createdAt: "desc" }],
      });

  if (!run) {
    return NextResponse.json({ ok: true, summary: null });
  }

  const lines = await prisma.hrPayrollLine.findMany({
    where: { runId: run.id },
  });

  let percepciones = 0;
  let deducciones = 0;
  let aportaciones = 0;
  const people = new Set<string>();

  for (const line of lines) {
    if (line.personIdentifier) {
      people.add(line.personIdentifier);
    }

    if (line.lineType === "percepciones") {
      percepciones += line.amount;
    } else if (line.lineType === "deducciones") {
      deducciones += line.amount;
    } else if (line.lineType === "aportaciones") {
      aportaciones += line.amount;
    }
  }

  const neto = percepciones - deducciones - aportaciones;

  return NextResponse.json({
    ok: true,
    summary: {
      periodStart: run.periodStart.toISOString(),
      periodEnd: run.periodEnd.toISOString(),
      frequency: run.frequency,
      locationCode: run.locationCode,
      percepciones,
      deducciones,
      aportaciones,
      neto,
      peopleCount: people.size,
    },
  });
}
