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

const PAYMENT_STATUS_KEYS = new Set(Object.values(HrCompliancePaymentStatus));

function parsePaymentStatus(value?: string | null): HrCompliancePaymentStatus | undefined {
  if (!value) {
    return undefined;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return undefined;
  }
  return PAYMENT_STATUS_KEYS.has(trimmed as HrCompliancePaymentStatus) ? (trimmed as HrCompliancePaymentStatus) : 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 payments." }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const obligationId = searchParams.get("obligationId") ?? undefined;

  const payments = await prisma.hrCompliancePayment.findMany({
    where: {
      ...(obligationId ? { obligationId } : {}),
    },
    orderBy: [{ paymentDate: "desc" }],
    take: 400,
  });

  return NextResponse.json({
    ok: true,
    payments: payments.map((item) => ({
      id: item.id,
      obligationId: item.obligationId,
      paymentDate: item.paymentDate.toISOString(),
      amount: item.amount,
      status: item.status,
      referencePeriod: item.referencePeriod,
      receiptUrl: item.receiptUrl,
      note: item.note,
    })),
  });
}

type PaymentInput = {
  obligationId?: string;
  paymentDate?: string;
  amount?: number;
  status?: string;
  referencePeriod?: string | null;
  receiptUrl?: string | null;
  note?: string | null;
};

export async function POST(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 create payments." }, { status: 403 });
  }

  const body = (await request.json().catch(() => ({}))) as PaymentInput;
  if (!body.obligationId || !body.paymentDate || body.amount === undefined) {
    return NextResponse.json({ error: "obligationId, paymentDate, and amount are required." }, { status: 400 });
  }

  const status = parsePaymentStatus(body.status);

  const payment = await prisma.hrCompliancePayment.create({
    data: {
      obligationId: body.obligationId,
      paymentDate: new Date(body.paymentDate),
      amount: body.amount,
      status: status ?? "paid",
      referencePeriod: body.referencePeriod ?? null,
      receiptUrl: body.receiptUrl ?? null,
      note: body.note ?? null,
      createdById: session.user.id,
    },
  });

  return NextResponse.json({ ok: true, id: payment.id });
}
