import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
import { parseTruckEventPayload } from "@/lib/truck-schedule-shared";
import { prisma } from "@/lib/prisma";
import { prismaMutationErrorResponse } from "@/lib/prisma-route-error";
import { getSessionUserId } from "@/lib/session";

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: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Corps invalide" }, { status: 400 });
  }

  if (body === null || typeof body !== "object") {
    return NextResponse.json({ error: "Corps invalide" }, { status: 400 });
  }

  const data = parseTruckEventPayload(body as Record<string, unknown>);
  if (!data) {
    return NextResponse.json(
      { error: "Date (AAAA-MM-JJ) et lieu requis" },
      { status: 400 }
    );
  }

  try {
    const row = await prisma.truckEvent.update({
      where: { id },
      data,
    });
    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 {
    await prisma.truckEvent.delete({ where: { id } });
    revalidatePath("/");
    return NextResponse.json({ ok: true });
  } catch (e) {
    return prismaMutationErrorResponse(e);
  }
}
