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

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

export async function POST(
  request: NextRequest,
  { params }: { params: { section: string } },
) {
  const config = getSectionConfig(params.section);
  if (!config) {
    return NextResponse.json({ error: "Unknown section" }, { status: 404 });
  }

  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().catch(() => ({}));
  const lang = body.lang ?? "en";
  const model = (prisma as any)[config.model];
  const timestamp = new Date();

  const draft = await model.findFirst({
    where: { lang, status: ContentStatus.DRAFT },
    orderBy: { updatedAt: "desc" },
  });

  if (!draft) {
    return NextResponse.json(
      { error: "No draft found to publish" },
      { status: 400 },
    );
  }

  const published = await model.findFirst({
    where: { lang, status: ContentStatus.PUBLISHED },
    orderBy: { updatedAt: "desc" },
  });

  const {
    id: draftId,
    createdAt: _cAt,
    updatedAt: _uAt,
    status: _s,
    ...rest
  } = draft;
  const publishData = {
    ...rest,
    lang,
    status: ContentStatus.PUBLISHED,
    version: draft.version,
    publishedBy: user.id,
    publishedAt: timestamp,
    updatedAt: timestamp,
  };

  let record;
  if (published) {
    record = await model.update({
      where: { id: published.id },
      data: publishData,
    });
  } else {
    record = await model.create({
      data: publishData,
    });
  }

  await saveContentVersion(
    params.section,
    record.id,
    draft.version,
    record,
    user.id,
  );

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