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 ingredients = await prisma.ingredient.findMany({
    orderBy: { name: "asc" },
  });
  return NextResponse.json(ingredients);
}

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

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

  const ingredient = await prisma.ingredient.create({
    data: { name, price, imageUrl },
  });
  revalidatePath("/");
  return NextResponse.json(ingredient);
}
