/**
 * POST /api/page-studio/save
 *
 * Upserts a StudioPage. If `id` is supplied the row is updated in
 * place; otherwise a new row is created keyed on (brandId, slug).
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";
export const maxDuration = 60;

interface SaveBody {
  id?: string;
  brandId?: string;
  title?: string;
  slug?: string;
  purpose?: string;
  sections?: unknown;
  branding?: unknown;
  settings?: unknown;
  status?: string;
  thumbnail?: string | null;
}

function slugify(input: string): string {
  return input.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0, 80) || "untitled";
}

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = (await req.json().catch(() => null)) as SaveBody | null;
  if (!body?.brandId || !body.title) {
    return NextResponse.json({ error: "brandId and title are required" }, { status: 400 });
  }

  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const slug = slugify(body.slug || body.title);
  const data = {
    title: body.title,
    purpose: body.purpose || "lead_generation",
    sections: (body.sections ?? []) as object,
    branding: (body.branding ?? {}) as object,
    settings: (body.settings ?? {}) as object,
    status: body.status || "draft",
    thumbnail: body.thumbnail ?? null,
  };

  let page;
  if (body.id) {
    // Explicit update — keeps the slug stable unless the client changed it.
    page = await prisma.studioPage.update({
      where: { id: body.id },
      data: { ...data, slug },
    });
  } else {
    // Upsert on (brandId, slug) so re-saving a generated page overwrites.
    page = await prisma.studioPage.upsert({
      where: { brandId_slug: { brandId: body.brandId, slug } },
      create: { brandId: body.brandId, slug, ...data },
      update: data,
    });
  }

  return NextResponse.json({ page });
}
