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

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

  const now = new Date();
  const ago7 = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  const ago30 = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  const ago90 = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);

  const [last, last7, last30, last90] = await Promise.all([
    prisma.reading.findFirst({ where: { userId }, orderBy: { measuredAt: "desc" } }),
    prisma.reading.findMany({ where: { userId, measuredAt: { gte: ago7 } } }),
    prisma.reading.findMany({ where: { userId, measuredAt: { gte: ago30 } } }),
    prisma.reading.findMany({ where: { userId, measuredAt: { gte: ago90 } } }),
  ]);

  const summarize = (rows: typeof last7) => {
    if (rows.length === 0) {
      return { count: 0, avg: null, inRangePct: null, hypoCount: 0, hyperCount: 0 };
    }
    const sum = rows.reduce((acc, r) => acc + r.value, 0);
    const avg = sum / rows.length;
    let inRange = 0, hypo = 0, hyper = 0;
    for (const r of rows) {
      const s = statusFor(r.value, r.moment as Moment);
      if (s === "in-range") inRange++;
      else if (s === "hypo") hypo++;
      else hyper++;
    }
    return { count: rows.length, avg, inRangePct: (inRange / rows.length) * 100, hypoCount: hypo, hyperCount: hyper };
  };

  const s7 = summarize(last7);
  const s30 = summarize(last30);
  const s90 = summarize(last90);

  return NextResponse.json({
    last,
    week: s7,
    month: s30,
    quarter: s90,
    estimatedHbA1c: s90.avg ? estimateHbA1c(s90.avg) : null,
  });
}
