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

type CreateUpdateBody = {
  title?: string;
  body?: string;
  severity?: HrUpdateSeverity;
  audience?: string;
  status?: string;
  publishedAt?: string | null;
};

const VALID_SEVERITY = new Set<HrUpdateSeverity>([
  HrUpdateSeverity.info,
  HrUpdateSeverity.warning,
  HrUpdateSeverity.critical,
]);

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 canManage = canManageHumanCapital(session.user.role, session.user.department);

  const updates = await prisma.hrUpdate.findMany({
    where: canManage
      ? undefined
      : {
          status: "published",
        },
    orderBy: [{ publishedAt: "desc" }, { createdAt: "desc" }],
    take: 40,
  });

  return NextResponse.json({
    ok: true,
    updates: updates.map((update) => ({
      id: update.id,
      title: update.title,
      body: update.body,
      severity: update.severity,
      audience: update.audience,
      status: update.status,
      publishedAt: update.publishedAt ? update.publishedAt.toISOString() : null,
      createdAt: update.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 publish updates." }, { status: 403 });
  }

  const body = (await request.json()) as CreateUpdateBody;
  const title = body.title?.trim() ?? "";
  const content = body.body?.trim() ?? "";
  const severity = body.severity && VALID_SEVERITY.has(body.severity) ? body.severity : HrUpdateSeverity.info;
  const status = body.status?.trim() || "published";
  const publishedAt = body.publishedAt ? new Date(body.publishedAt) : new Date();

  if (!title || !content) {
    return NextResponse.json({ error: "title and body are required." }, { status: 400 });
  }

  const update = await prisma.hrUpdate.create({
    data: {
      title,
      body: content,
      severity,
      audience: body.audience?.trim() || "hc_leadership",
      status,
      publishedAt: Number.isNaN(publishedAt.getTime()) ? new Date() : publishedAt,
      authorId: session.user.id,
    },
  });

  return NextResponse.json({
    ok: true,
    update: {
      id: update.id,
      title: update.title,
      body: update.body,
      severity: update.severity,
      audience: update.audience,
      status: update.status,
      publishedAt: update.publishedAt ? update.publishedAt.toISOString() : null,
      createdAt: update.createdAt.toISOString(),
    },
  });
}
