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 { validatePreviewToken } 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) {
  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");
  const upcoming = url.searchParams.get("upcoming") === "true";
  const take = Number(url.searchParams.get("limit") || 50);

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

  const where: any = { lang, status };
  if (upcoming) {
    where.startAt = { gte: new Date() };
  }

  const records = await prisma.events.findMany({
    where,
    orderBy: { startAt: "asc" },
    take,
  });

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

export async function PATCH(request: NextRequest) {
  const user = await getStaffSession();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const {
    id,
    lang = "en",
    title,
    description,
    startAt,
    endAt,
    location,
    ctaLabel,
    ctaHref,
    heroImage,
    tags = [],
    audience,
    publishToSite = false,
    publishToSocial = false,
    campaignId,
  } = body;

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

  const timestamp = new Date();
  let record;

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

    record = await prisma.events.update({
      where: { id },
      data: {
        title,
        description,
        startAt: new Date(startAt),
        endAt: endAt ? new Date(endAt) : null,
        location,
        ctaLabel,
        ctaHref,
        heroImage,
        tags,
        audience,
        publishToSite,
        publishToSocial,
        campaignId,
        lang,
        status: ContentStatus.DRAFT,
        version: (existing.version || 0) + 1,
        updatedBy: user.id,
        updatedAt: timestamp,
      },
    });
  } else {
    record = await prisma.events.create({
      data: {
        title,
        description,
        startAt: new Date(startAt),
        endAt: endAt ? new Date(endAt) : null,
        location,
        ctaLabel,
        ctaHref,
        heroImage,
        tags,
        audience,
        publishToSite,
        publishToSocial,
        campaignId,
        lang,
        status: ContentStatus.DRAFT,
        version: 1,
        createdBy: user.id,
        updatedBy: user.id,
        updatedAt: timestamp,
      },
    });
  }

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