import { NextResponse, type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
const ContentStatus = { DRAFT: "DRAFT", PUBLISHED: "PUBLISHED" } as const;
import { getStaffSession } from "@/lib/staff-session";
import { saveContentVersion } from "@/lib/site-content/preview";

const ADMIN_ROLES = ["ADMIN", "SUPER_ADMIN"];

export async function POST(request: NextRequest) {
  const user = await getStaffSession();
  if (!user || !ADMIN_ROLES.includes(user.role)) {
    return NextResponse.json(
      { error: "Admin role required to publish" },
      { status: 403 },
    );
  }

  const body = await request.json();
  const { id } = body;

  if (!id) {
    return NextResponse.json({ error: "id is required" }, { status: 400 });
  }

  const draft = await prisma.announcements.findUnique({ where: { id } });
  if (!draft) {
    return NextResponse.json(
      { error: "Announcement not found" },
      { status: 404 },
    );
  }

  const timestamp = new Date();

  const record = await prisma.announcements.update({
    where: { id },
    data: {
      status: ContentStatus.PUBLISHED,
      publishedBy: user.id,
      publishedAt: timestamp,
      updatedAt: timestamp,
    },
  });

  await saveContentVersion(
    "announcements",
    record.id,
    record.version ?? 1,
    record,
    user.id,
  );

  return NextResponse.json({ data: record });
}
