import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
import { WAFFLE_CATEGORIES } from "@/lib/constants";
import { normalizeImageUrl } from "@/lib/image-url";
import { parseStrictBoolean } from "@/lib/json-fields";
import { prisma } from "@/lib/prisma";
import { prismaMutationErrorResponse } from "@/lib/prisma-route-error";
import { getSessionUserId } from "@/lib/session";
import { deleteUploadAssetIfAny } from "@/lib/upload-asset";
import {
  parseIngredientIds,
  validateIngredientIds,
  waffleIngredientInclude,
} from "@/lib/waffle-ingredients";

const CATEGORIES: Set<string> = new Set(Object.values(WAFFLE_CATEGORIES));

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

  const name = String(body.name ?? "").trim();
  const ingredients = String(body.ingredients ?? "").trim();
  const price = Number(body.price);
  const isNewParsed = parseStrictBoolean(body.isNew, "isNew", false);
  if (!isNewParsed.ok) {
    return NextResponse.json({ error: isNewParsed.error }, { status: 400 });
  }
  const isNew = isNewParsed.value;
  const category = String(body.category ?? "").trim();
  const imageUrl = normalizeImageUrl(body.imageUrl);

  if (!name || !ingredients || Number.isNaN(price) || price < 0) {
    return NextResponse.json({ error: "Données invalides" }, { status: 400 });
  }
  if (!CATEGORIES.has(category)) {
    return NextResponse.json({ error: "Catégorie invalide" }, { status: 400 });
  }
  if (
    body.imageUrl != null &&
    String(body.imageUrl).trim() !== "" &&
    imageUrl === null
  ) {
    return NextResponse.json({ error: "URL d’image invalide" }, { status: 400 });
  }

  const parsedIds = parseIngredientIds(body.ingredientIds);
  if (parsedIds !== null && !(await validateIngredientIds(parsedIds))) {
    return NextResponse.json({ error: "Ingrédient inconnu" }, { status: 400 });
  }

  try {
    const previous = await prisma.waffle.findUnique({
      where: { id },
      select: { imageUrl: true },
    });
    const waffle = await prisma.waffle.update({
      where: { id },
      data: {
        name,
        ingredients,
        price,
        isNew,
        category,
        imageUrl,
        ...(parsedIds !== null
          ? {
              ingredientItems: {
                set: parsedIds.map((ingredientId) => ({ id: ingredientId })),
              },
            }
          : {}),
      },
      include: waffleIngredientInclude,
    });
    if (previous?.imageUrl && previous.imageUrl !== waffle.imageUrl) {
      await deleteUploadAssetIfAny(previous.imageUrl);
    }
    revalidatePath("/");
    return NextResponse.json(waffle);
  } 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.waffle.delete({ where: { id } });
    await deleteUploadAssetIfAny(row.imageUrl);
    revalidatePath("/");
    return NextResponse.json({ ok: true });
  } catch (e) {
    return prismaMutationErrorResponse(e);
  }
}
