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

type CreateLifecycleBody = {
  userId?: string;
  eventType?: EmployeeLifecycleEventType;
  effectiveAt?: string;
  reason?: string;
  isVoluntary?: boolean | null;
  metadata?: Record<string, unknown> | null;
};

const VALID_TYPES = new Set<EmployeeLifecycleEventType>([
  EmployeeLifecycleEventType.hire,
  EmployeeLifecycleEventType.transfer,
  EmployeeLifecycleEventType.leave,
  EmployeeLifecycleEventType.termination,
  EmployeeLifecycleEventType.rehire,
]);

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

  const { searchParams } = new URL(request.url);
  const userId = searchParams.get("userId") ?? undefined;
  const events = await prisma.employeeLifecycleEvent.findMany({
    where: {
      ...(userId ? { userId } : {}),
    },
    orderBy: [{ effectiveAt: "desc" }, { createdAt: "desc" }],
    take: 300,
  });

  return NextResponse.json({
    ok: true,
    events: events.map((event) => ({
      id: event.id,
      userId: event.userId,
      eventType: event.eventType,
      effectiveAt: event.effectiveAt.toISOString(),
      reason: event.reason,
      isVoluntary: event.isVoluntary,
      metadata: event.metadata ?? null,
      createdById: event.createdById,
      createdAt: event.createdAt.toISOString(),
    })),
  });
}

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

  const body = (await request.json()) as CreateLifecycleBody;
  if (!body.userId || !body.eventType || !VALID_TYPES.has(body.eventType)) {
    return NextResponse.json({ error: "userId and valid eventType are required." }, { status: 400 });
  }

  const effectiveAt = body.effectiveAt ? new Date(body.effectiveAt) : new Date();
  if (Number.isNaN(effectiveAt.getTime())) {
    return NextResponse.json({ error: "Invalid effectiveAt date." }, { status: 400 });
  }

  const event = await prisma.employeeLifecycleEvent.create({
    data: {
      userId: body.userId,
      eventType: body.eventType,
      effectiveAt,
      reason: body.reason?.trim() || null,
      isVoluntary: typeof body.isVoluntary === "boolean" ? body.isVoluntary : null,
      metadata: body.metadata ? (body.metadata as Prisma.InputJsonValue) : undefined,
      createdById: session.user.id,
    },
  });

  return NextResponse.json({
    ok: true,
    event: {
      id: event.id,
      userId: event.userId,
      eventType: event.eventType,
      effectiveAt: event.effectiveAt.toISOString(),
      reason: event.reason,
      isVoluntary: event.isVoluntary,
      metadata: event.metadata ?? null,
      createdById: event.createdById,
      createdAt: event.createdAt.toISOString(),
    },
  });
}
