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

const PAYROLL_FREQUENCIES = new Set(Object.values(HrPayrollFrequency));

function parsePayrollFrequency(value?: string | null): HrPayrollFrequency | undefined {
  if (!value) {
    return undefined;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return undefined;
  }
  return PAYROLL_FREQUENCIES.has(trimmed as HrPayrollFrequency) ? (trimmed as HrPayrollFrequency) : undefined;
}

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 runs." }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const frequency = parsePayrollFrequency(searchParams.get("frequency"));
  const locationCode = searchParams.get("location") ?? undefined;

  const runs = await prisma.hrPayrollRun.findMany({
    where: {
      department: "capital_humano",
      ...(frequency ? { frequency } : {}),
      ...(locationCode ? { locationCode } : {}),
    },
    orderBy: [{ periodEnd: "desc" }, { createdAt: "desc" }],
    take: 200,
  });

  return NextResponse.json({
    ok: true,
    runs: runs.map((run) => ({
      id: run.id,
      periodStart: run.periodStart.toISOString(),
      periodEnd: run.periodEnd.toISOString(),
      frequency: run.frequency,
      locationCode: run.locationCode,
      status: run.status,
      source: run.source,
      externalRef: run.externalRef,
      importedAt: run.importedAt.toISOString(),
    })),
  });
}
