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

function normalizeStatus(param: string | null): ContentStatus {
  if (param && param.toUpperCase() === "DRAFT") {
    return ContentStatus.DRAFT;
  }
  return ContentStatus.PUBLISHED;
}

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

  const url = new URL(request.url);
  const lang = url.searchParams.get("lang") ?? "en";
  const status = normalizeStatus(url.searchParams.get("status"));
  const preview = url.searchParams.get("preview");

  if (status === ContentStatus.DRAFT) {
    const [user, previewOk] = await Promise.all([
      getStaffSession(),
      validatePreviewToken(preview, params.section, lang),
    ]);
    if (!user && !previewOk) {
      return NextResponse.json(
        { error: "Draft access requires staff session or preview token" },
        { status: 401 },
      );
    }
  }

  const model = (prisma as any)[config.model];
  const record = await model.findFirst({
    where: { lang, status },
    orderBy: { updatedAt: "desc" },
  });

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

export async function PATCH(
  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) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const lang = body.lang ?? "en";
  const filtered = filterFields(body, config.allowedFields);

  if (Object.keys(filtered).length === 0) {
    return NextResponse.json(
      { error: "No updatable fields provided" },
      { status: 400 },
    );
  }

  const model = (prisma as any)[config.model];
  const existing = await model.findFirst({
    where: { lang, status: ContentStatus.DRAFT },
    orderBy: { updatedAt: "desc" },
  });

  const nextVersion = existing ? existing.version + 1 : 1;
  const timestamp = new Date();

  let record;
  if (existing) {
    record = await model.update({
      where: { id: existing.id },
      data: {
        ...filtered,
        lang,
        status: ContentStatus.DRAFT,
        version: nextVersion,
        updatedBy: user.id,
        updatedAt: timestamp,
      },
    });
  } else {
    record = await model.create({
      data: {
        ...filtered,
        lang,
        status: ContentStatus.DRAFT,
        version: nextVersion,
        createdBy: user.id,
        updatedBy: user.id,
        updatedAt: timestamp,
      },
    });
  }

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

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