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: { name?: string; price?: number; imageUrl?: string | null };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Corps invalide" }, { status: 400 });
  }

  const name = String(body.name ?? "").trim();
  const price = Number(body.price);
  const imageUrl = normalizeImageUrl(body.imageUrl);

  if (!name || Number.isNaN(price) || price < 0) {
    return NextResponse.json({ error: "Données invalides" }, { 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.ingredient.findUnique({
      where: { id },
      select: { imageUrl: true },
    });
    const ingredient = await prisma.ingredient.update({
      where: { id },
      data: { name, price, imageUrl },
    });
    if (previous?.imageUrl && previous.imageUrl !== ingredient.imageUrl) {
      await deleteUploadAssetIfAny(previous.imageUrl);
    }
    revalidatePath("/");
    return NextResponse.json(ingredient);
  } 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.ingredient.delete({ where: { id } });
    await deleteUploadAssetIfAny(row.imageUrl);
    revalidatePath("/");
    return NextResponse.json({ ok: true });
  } catch (e) {
    return prismaMutationErrorResponse(e);
  }
}
