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";
import { ensureHumanCapitalWorkspaceBootstrap } from "@/lib/human-capital/workspace";

type RequirementInput = {
  id?: string;
  key?: string;
  label?: string;
  description?: string | null;
  fieldType?: string;
  isRequired?: boolean;
  isActive?: boolean;
  sortOrder?: number;
};

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

  await ensureHumanCapitalWorkspaceBootstrap();

  const requirements = await prisma.hrFileRequirement.findMany({
    where: { department: "capital_humano" },
    orderBy: [{ sortOrder: "asc" }, { label: "asc" }],
  });

  return NextResponse.json({
    ok: true,
    requirements: requirements.map((req) => ({
      id: req.id,
      key: req.key,
      label: req.label,
      description: req.description,
      fieldType: req.fieldType,
      isRequired: req.isRequired,
      isActive: req.isActive,
      sortOrder: req.sortOrder,
    })),
  });
}

export async function PUT(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 edit requirements." }, { status: 403 });
  }

  const body = (await request.json().catch(() => ({}))) as { requirements?: RequirementInput[] };
  if (!Array.isArray(body.requirements)) {
    return NextResponse.json({ error: "requirements array is required." }, { status: 400 });
  }

  const cleaned = body.requirements
    .map((item, idx) => ({
      id: item.id,
      key: item.key?.trim() || undefined,
      label: item.label?.trim() || "",
      description: item.description?.trim() || null,
      fieldType: item.fieldType?.trim() || "document",
      isRequired: item.isRequired ?? true,
      isActive: item.isActive ?? true,
      sortOrder: Number.isFinite(item.sortOrder) ? Number(item.sortOrder) : idx * 10,
    }))
    .filter((item) => item.label.length > 0);

  if (cleaned.length === 0) {
    return NextResponse.json({ error: "At least one valid requirement is required." }, { status: 400 });
  }

  const updated = await prisma.$transaction(
    cleaned.map((item) => {
      if (item.id) {
        return prisma.hrFileRequirement.update({
          where: { id: item.id },
          data: {
            key: item.key ?? undefined,
            label: item.label,
            description: item.description,
            fieldType: item.fieldType,
            isRequired: item.isRequired,
            isActive: item.isActive,
            sortOrder: item.sortOrder,
            updatedById: session.user.id,
          },
        });
      }

      if (!item.key) {
        throw new Error("key is required for new requirements.");
      }

      return prisma.hrFileRequirement.upsert({
        where: {
          department_key: {
            department: "capital_humano",
            key: item.key,
          },
        },
        update: {
          label: item.label,
          description: item.description,
          fieldType: item.fieldType,
          isRequired: item.isRequired,
          isActive: item.isActive,
          sortOrder: item.sortOrder,
          updatedById: session.user.id,
        },
        create: {
          department: "capital_humano",
          key: item.key,
          label: item.label,
          description: item.description,
          fieldType: item.fieldType,
          isRequired: item.isRequired,
          isActive: item.isActive,
          sortOrder: item.sortOrder,
          createdById: session.user.id,
          updatedById: session.user.id,
        },
      });
    })
  );

  return NextResponse.json({
    ok: true,
    requirements: updated.map((req) => ({
      id: req.id,
      key: req.key,
      label: req.label,
      description: req.description,
      fieldType: req.fieldType,
      isRequired: req.isRequired,
      isActive: req.isActive,
      sortOrder: req.sortOrder,
    })),
  });
}
