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

  await ensureEmployeeProfiles();

  const [targets, profiles] = await Promise.all([
    prisma.hrIdealOrgTarget.findMany({
      where: { department: "capital_humano", isActive: true },
      orderBy: [{ locationCode: "asc" }, { roleKey: "asc" }],
    }),
    prisma.employeeProfile.findMany({
      where: { employmentStatus: "active" },
      include: { user: { select: { departmentRole: true } } },
    }),
  ]);

  const actualByKey = 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}`;
    actualByKey.set(key, (actualByKey.get(key) ?? 0) + 1);
  }

  const rows = targets.map((target) => {
    const key = `${target.locationCode}::${target.roleKey}`;
    const actual = actualByKey.get(key) ?? 0;
    return {
      id: target.id,
      locationCode: target.locationCode,
      roleKey: target.roleKey,
      targetCount: target.targetCount,
      isActive: target.isActive,
      actualCount: actual,
      gap: target.targetCount - actual,
    };
  });

  return NextResponse.json({ ok: true, targets: rows });
}

type OrgTargetInput = {
  id?: string;
  locationCode?: string;
  roleKey?: string;
  targetCount?: number;
  isActive?: boolean;
};

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

  const body = (await request.json().catch(() => ({}))) as OrgTargetInput;
  if (!body.locationCode || !body.roleKey || body.targetCount === undefined) {
    return NextResponse.json({ error: "locationCode, roleKey, and targetCount are required." }, { status: 400 });
  }

  const target = await prisma.hrIdealOrgTarget.upsert({
    where: {
      department_locationCode_roleKey: {
        department: "capital_humano",
        locationCode: body.locationCode,
        roleKey: body.roleKey,
      },
    },
    update: {
      targetCount: body.targetCount,
      isActive: body.isActive ?? true,
      updatedById: session.user.id,
    },
    create: {
      department: "capital_humano",
      locationCode: body.locationCode,
      roleKey: body.roleKey,
      targetCount: body.targetCount,
      isActive: body.isActive ?? true,
      updatedById: session.user.id,
    },
  });

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

export async function PATCH(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 update org targets." }, { status: 403 });
  }

  const body = (await request.json().catch(() => ({}))) as OrgTargetInput;
  if (!body.id) {
    return NextResponse.json({ error: "id is required." }, { status: 400 });
  }

  await prisma.hrIdealOrgTarget.update({
    where: { id: body.id },
    data: {
      locationCode: body.locationCode ?? undefined,
      roleKey: body.roleKey ?? undefined,
      targetCount: body.targetCount ?? undefined,
      isActive: body.isActive ?? undefined,
      updatedById: session.user.id,
    },
  });

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