import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
import { parseTruckEventPayload } from "@/lib/truck-schedule-shared";
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 events = await prisma.truckEvent.findMany({
    orderBy: [{ eventDate: "asc" }, { createdAt: "asc" }],
  });
  return NextResponse.json(events);
}

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

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

  const row = await prisma.truckEvent.create({ data });
  revalidatePath("/");
  return NextResponse.json(row);
}
