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

const DEPARTMENT_KEYS = new Set(Object.values(DepartmentKey));

function parseDepartmentKey(value?: string | null): DepartmentKey | null {
  if (!value) {
    return null;
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return null;
  }
  return DEPARTMENT_KEYS.has(trimmed as DepartmentKey) ? (trimmed as DepartmentKey) : null;
}

export async function GET() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessHumanCapital(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const items = await prisma.hrCareerContent.findMany({
    where: {
      department: "capital_humano",
      contentType: "course",
      isActive: true,
    },
    orderBy: [{ createdAt: "desc" }],
    take: 100,
  });

  return NextResponse.json({
    ok: true,
    courses: items.map((item) => ({
      id: item.id,
      contentType: item.contentType,
      title: item.title,
      body: item.body,
      sourceDepartment: item.sourceDepartment,
      startsAt: item.startsAt ? item.startsAt.toISOString() : null,
      endsAt: item.endsAt ? item.endsAt.toISOString() : null,
      isActive: item.isActive,
      createdAt: item.createdAt.toISOString(),
    })),
  });
}

type ContentInput = {
  title?: string;
  body?: string;
  sourceDepartment?: string | null;
  startsAt?: string | null;
  endsAt?: string | null;
  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 publish courses." }, { status: 403 });
  }

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

  const item = await prisma.hrCareerContent.create({
    data: {
      department: "capital_humano",
      contentType: "course",
      title: body.title.trim(),
      body: body.body.trim(),
      sourceDepartment: parseDepartmentKey(body.sourceDepartment),
      startsAt: body.startsAt ? new Date(body.startsAt) : null,
      endsAt: body.endsAt ? new Date(body.endsAt) : null,
      isActive: body.isActive ?? true,
      createdById: session.user.id,
      updatedById: session.user.id,
    },
  });

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