import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
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 images = await prisma.galleryImage.findMany({
    orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
  });
  return NextResponse.json(images);
}

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

  let body: { imageUrl?: string; alt?: string; sortOrder?: number };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Corps invalide" }, { status: 400 });
  }

  const imageUrl = normalizeImageUrl(body.imageUrl);
  const alt = String(body.alt ?? "").trim();
  const sortOrder = Number.isFinite(Number(body.sortOrder))
    ? Number(body.sortOrder)
    : 0;

  if (!imageUrl || !alt) {
    return NextResponse.json(
      { error: "Image et texte alternatif requis" },
      { status: 400 }
    );
  }
  if (
    body.imageUrl != null &&
    String(body.imageUrl).trim() !== "" &&
    imageUrl === null
  ) {
    return NextResponse.json({ error: "URL d’image invalide" }, { status: 400 });
  }

  const row = await prisma.galleryImage.create({
    data: { imageUrl, alt, sortOrder },
  });
  revalidatePath("/");
  return NextResponse.json(row);
}
