import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
import {
  getCustomWaffleConfig,
  parseCustomWafflePayload,
} from "@/lib/custom-waffle-content";
import { DEFAULT_PUBLIC_SITE_COPY, SITE_CONTENT_ID } from "@/lib/site-content-defaults";
import { prisma } from "@/lib/prisma";
import { getSessionUserId } from "@/lib/session";

export async function GET() {
  const userId = await getSessionUserId();
  if (!userId) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  return NextResponse.json(await getCustomWaffleConfig());
}

export async function PUT(request: Request) {
  const userId = await getSessionUserId();
  if (!userId) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Corps invalide" }, { status: 400 });
  }

  if (body === null || typeof body !== "object") {
    return NextResponse.json({ error: "Corps invalide" }, { status: 400 });
  }

  const parsed = parseCustomWafflePayload(body as Record<string, unknown>);
  if (parsed.error || !parsed.data) {
    return NextResponse.json({ error: parsed.error }, { status: 400 });
  }

  const { data } = parsed;

  await prisma.siteContent.upsert({
    where: { id: SITE_CONTENT_ID },
    create: {
      id: SITE_CONTENT_ID,
      ...DEFAULT_PUBLIC_SITE_COPY,
      customWaffleTitle: data.title,
      customWaffleDescription: data.description,
      customWaffleBasePrice: data.basePrice,
      customWaffleImageUrl: data.imageUrl,
      customWaffleVisible: data.visible,
    },
    update: {
      customWaffleTitle: data.title,
      customWaffleDescription: data.description,
      customWaffleBasePrice: data.basePrice,
      customWaffleImageUrl: data.imageUrl,
      customWaffleVisible: data.visible,
    },
  });

  revalidatePath("/");
  return NextResponse.json({ ok: true });
}
