import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
import {
  DEFAULT_PUBLIC_SITE_COPY,
  SITE_CONTENT_ID,
} from "@/lib/site-content-defaults";
import { parseHoursPayload } from "@/lib/site-content";
import { normalizeImageUrl } from "@/lib/image-url";
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 });
  }

  const row = await prisma.siteContent.findUnique({
    where: { id: SITE_CONTENT_ID },
  });
  if (!row) {
    return NextResponse.json({
      ...DEFAULT_PUBLIC_SITE_COPY,
      heroTextOverImage: DEFAULT_PUBLIC_SITE_COPY.heroTextOverImage,
      uploadImageWidth: 1920,
      uploadImageHeight: 1080,
    });
  }

  return NextResponse.json({
    logoUrl: row.logoUrl ?? DEFAULT_PUBLIC_SITE_COPY.logoUrl,
    heroEyebrow: row.heroEyebrow,
    heroTitle: row.heroTitle,
    heroSubtitle: row.heroSubtitle,
    heroBackgroundImageUrl:
      row.heroBackgroundImageUrl ?? DEFAULT_PUBLIC_SITE_COPY.heroBackgroundImageUrl,
    heroTextOverImage: row.heroTextOverImage ?? true,
    menuIntro: row.menuIntro,
    galleryIntro: row.galleryIntro,
    scheduleIntro: row.scheduleIntro ?? "",
    uploadImageWidth: row.uploadImageWidth ?? 1920,
    uploadImageHeight: row.uploadImageHeight ?? 1080,
    hours: row.hours,
  });
}

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 b = body as Record<string, unknown>;
  const hours = parseHoursPayload(b.hours);
  if (hours === null) {
    return NextResponse.json(
      { error: "Horaires : tableau de { days, hours } attendu" },
      { status: 400 }
    );
  }

  const rawW = typeof b.uploadImageWidth === "number"
    ? b.uploadImageWidth
    : Number(String(b.uploadImageWidth ?? ""));
  const rawH = typeof b.uploadImageHeight === "number"
    ? b.uploadImageHeight
    : Number(String(b.uploadImageHeight ?? ""));
  const uploadImageWidth = Number.isFinite(rawW) ? Math.trunc(rawW) : 1920;
  const uploadImageHeight = Number.isFinite(rawH) ? Math.trunc(rawH) : 1080;
  if (
    uploadImageWidth < 320 ||
    uploadImageWidth > 8000 ||
    uploadImageHeight < 240 ||
    uploadImageHeight > 8000
  ) {
    return NextResponse.json(
      { error: "Résolution upload invalide (ex: 1920×1080)" },
      { status: 400 }
    );
  }

  const data = {
    logoUrl:
      normalizeImageUrl(String(b.logoUrl ?? "")) ??
      DEFAULT_PUBLIC_SITE_COPY.logoUrl,
    heroEyebrow: String(b.heroEyebrow ?? "").trim(),
    heroTitle: String(b.heroTitle ?? "").trim(),
    heroSubtitle: String(b.heroSubtitle ?? "").trim(),
    heroBackgroundImageUrl:
      normalizeImageUrl(String(b.heroBackgroundImageUrl ?? "")) ??
      DEFAULT_PUBLIC_SITE_COPY.heroBackgroundImageUrl,
    heroTextOverImage: b.heroTextOverImage !== false,
    menuIntro: String(b.menuIntro ?? "").trim(),
    galleryIntro: String(b.galleryIntro ?? "").trim(),
    scheduleIntro: String(b.scheduleIntro ?? "").trim(),
    uploadImageWidth,
    uploadImageHeight,
    hours,
  };

  await prisma.siteContent.upsert({
    where: { id: SITE_CONTENT_ID },
    create: {
      id: SITE_CONTENT_ID,
      ...data,
    },
    update: data,
  });

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