import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { MOMENT_LABELS, type Moment } from "@/lib/glycemia";
import { format } from "date-fns";

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

  const readings = await prisma.reading.findMany({
    where: { userId },
    orderBy: { measuredAt: "desc" },
  });

  const header = ["Date", "Heure", "Moment", "Glycémie (g/L)", "Notes"].join(";");
  const rows = readings.map((r) => {
    const d = new Date(r.measuredAt);
    return [
      format(d, "yyyy-MM-dd"),
      format(d, "HH:mm"),
      MOMENT_LABELS[r.moment as Moment] ?? r.moment,
      r.value.toFixed(2).replace(".", ","),
      (r.notes ?? "").replace(/[\r\n;]/g, " "),
    ].join(";");
  });

  const csv = "﻿" + [header, ...rows].join("\r\n");
  const filename = `diabetix-${format(new Date(), "yyyyMMdd-HHmm")}.csv`;

  return new Response(csv, {
    headers: {
      "Content-Type": "text/csv; charset=utf-8",
      "Content-Disposition": `attachment; filename="${filename}"`,
    },
  });
}
