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

const VACANCY_STATUS_KEYS = new Set(Object.values(HrVacancyStatus));

function parseVacancyStatus(value?: string | null): HrVacancyStatus | undefined {
  if (!value) {
    return undefined;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return undefined;
  }
  return VACANCY_STATUS_KEYS.has(trimmed as HrVacancyStatus) ? (trimmed as HrVacancyStatus) : undefined;
}

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

  const vacancies = await prisma.hrVacancy.findMany({
    where: { department: "capital_humano" },
    orderBy: [{ openedAt: "desc" }, { createdAt: "desc" }],
    take: 400,
  });

  return NextResponse.json({
    ok: true,
    vacancies: vacancies.map((vacancy) => ({
      id: vacancy.id,
      locationCode: vacancy.locationCode,
      roleKey: vacancy.roleKey,
      title: vacancy.title,
      status: vacancy.status,
      priority: vacancy.priority,
      openedAt: vacancy.openedAt.toISOString(),
      targetStartAt: vacancy.targetStartAt ? vacancy.targetStartAt.toISOString() : null,
      closedAt: vacancy.closedAt ? vacancy.closedAt.toISOString() : null,
      notes: vacancy.notes,
    })),
  });
}

type VacancyInput = {
  id?: string;
  locationCode?: string;
  roleKey?: string;
  title?: string;
  status?: string;
  priority?: string;
  openedAt?: string;
  targetStartAt?: string | null;
  closedAt?: string | null;
  notes?: 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 vacancies." }, { status: 403 });
  }

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

  const status = parseVacancyStatus(body.status);
  const vacancy = await prisma.hrVacancy.create({
    data: {
      department: "capital_humano",
      locationCode: body.locationCode,
      roleKey: body.roleKey,
      title: body.title,
      status: status ?? "open",
      priority: body.priority ?? "medium",
      openedAt: body.openedAt ? new Date(body.openedAt) : new Date(),
      targetStartAt: body.targetStartAt ? new Date(body.targetStartAt) : null,
      closedAt: body.closedAt ? new Date(body.closedAt) : null,
      notes: body.notes ?? null,
      createdById: session.user.id,
      updatedById: session.user.id,
    },
  });

  return NextResponse.json({ ok: true, vacancyId: vacancy.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 vacancies." }, { status: 403 });
  }

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

  const parsedStatus = parseVacancyStatus(body.status);

  await prisma.hrVacancy.update({
    where: { id: body.id },
    data: {
      locationCode: body.locationCode ?? undefined,
      roleKey: body.roleKey ?? undefined,
      title: body.title ?? undefined,
      status: parsedStatus ?? undefined,
      priority: body.priority ?? undefined,
      openedAt: body.openedAt ? new Date(body.openedAt) : undefined,
      targetStartAt: body.targetStartAt === null ? null : body.targetStartAt ? new Date(body.targetStartAt) : undefined,
      closedAt: body.closedAt === null ? null : body.closedAt ? new Date(body.closedAt) : undefined,
      notes: body.notes ?? undefined,
      updatedById: session.user.id,
    },
  });

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