import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export async function DELETE(
  _request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session?.user?.id) return NextResponse.json({ error: "Non authentifié" }, { status: 401 });

  const { id } = await params;
  const numericId = Number(id);
  if (!Number.isInteger(numericId)) {
    return NextResponse.json({ error: "ID invalide" }, { status: 400 });
  }

  const reading = await prisma.reading.findUnique({ where: { id: numericId }, select: { userId: true } });
  if (!reading || reading.userId !== session.user.id) {
    return NextResponse.json({ error: "Relevé introuvable" }, { status: 404 });
  }

  await prisma.reading.delete({ where: { id: numericId } });
  return NextResponse.json({ ok: true });
}

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session?.user?.id) return NextResponse.json({ error: "Non authentifié" }, { status: 401 });

  const { id } = await params;
  const numericId = Number(id);
  if (!Number.isInteger(numericId)) {
    return NextResponse.json({ error: "ID invalide" }, { status: 400 });
  }

  const reading = await prisma.reading.findUnique({ where: { id: numericId }, select: { userId: true } });
  if (!reading || reading.userId !== session.user.id) {
    return NextResponse.json({ error: "Relevé introuvable" }, { status: 404 });
  }

  const body = await request.json().catch(() => null);
  if (!body) return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });

  const data: Record<string, unknown> = {};
  if (typeof body.value === "number" || typeof body.value === "string") {
    const v = typeof body.value === "string" ? parseFloat(body.value.replace(",", ".")) : body.value;
    if (Number.isFinite(v) && v > 0 && v <= 6) data.value = v;
  }
  if (typeof body.notes === "string" || body.notes === null) {
    data.notes = body.notes?.trim() || null;
  }
  if (typeof body.measuredAt === "string") {
    data.measuredAt = new Date(body.measuredAt);
  }
  if (typeof body.moment === "string" && ["FASTING", "LUNCH", "DINNER"].includes(body.moment)) {
    data.moment = body.moment;
  }

  const updated = await prisma.reading.update({ where: { id: numericId }, data });
  return NextResponse.json(updated);
}
