import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
import { normalizeImageUrl } from "@/lib/image-url";
import { prisma } from "@/lib/prisma";
import { prismaMutationErrorResponse } from "@/lib/prisma-route-error";
import { getSessionUserId } from "@/lib/session";
import { deleteUploadAssetIfAny } from "@/lib/upload-asset";

type Params = { params: Promise<{ id: string }> };

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

  const { id } = await params;

  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 });
  }

  try {
    const previous = await prisma.galleryImage.findUnique({
      where: { id },
      select: { imageUrl: true },
    });
    const row = await prisma.galleryImage.update({
      where: { id },
      data: { imageUrl, alt, sortOrder },
    });
    if (previous?.imageUrl && previous.imageUrl !== row.imageUrl) {
      await deleteUploadAssetIfAny(previous.imageUrl);
    }
    revalidatePath("/");
    return NextResponse.json(row);
  } catch (e) {
    return prismaMutationErrorResponse(e);
  }
}

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

  const { id } = await params;

  try {
    const row = await prisma.galleryImage.delete({ where: { id } });
    await deleteUploadAssetIfAny(row.imageUrl);
    revalidatePath("/");
    return NextResponse.json({ ok: true });
  } catch (e) {
    return prismaMutationErrorResponse(e);
  }
}
