import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { MOMENTS, type Moment } from "@/lib/glycemia";

const VALID_MOMENTS = MOMENTS.map(m => m.value);

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

  const url = new URL(request.url);
  const limit = Number(url.searchParams.get("limit") ?? 200);
  const from = url.searchParams.get("from");
  const to = url.searchParams.get("to");

  const where: Record<string, unknown> = { userId };
  if (from || to) {
    where.measuredAt = {
      ...(from ? { gte: new Date(from) } : {}),
      ...(to ? { lte: new Date(to) } : {}),
    };
  }

  const readings = await prisma.reading.findMany({
    where,
    orderBy: { measuredAt: "desc" },
    take: Math.min(Math.max(limit, 1), 1000),
  });

  return NextResponse.json(readings);
}

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

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

  const { measuredAt, moment, value, notes } = body as {
    measuredAt?: string;
    moment?: string;
    value?: number | string;
    notes?: string | null;
  };

  if (!moment || !VALID_MOMENTS.includes(moment as Moment)) {
    return NextResponse.json({ error: "Moment invalide" }, { status: 400 });
  }
  const numericValue = typeof value === "string" ? parseFloat(value.replace(",", ".")) : value;
  if (typeof numericValue !== "number" || Number.isNaN(numericValue) || numericValue <= 0) {
    return NextResponse.json({ error: "Valeur invalide" }, { status: 400 });
  }
  if (numericValue > 6) {
    return NextResponse.json({ error: "Valeur trop élevée (>6 g/L)" }, { status: 400 });
  }

  const reading = await prisma.reading.create({
    data: {
      userId,
      measuredAt: measuredAt ? new Date(measuredAt) : new Date(),
      moment,
      value: numericValue,
      notes: notes?.trim() || null,
    },
  });

  return NextResponse.json(reading, { status: 201 });
}
