import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { HistoryClient } from "@/app/historique/HistoryClient";

export const dynamic = "force-dynamic";
export const metadata = { title: "Historique — Diabetix" };

export default async function HistoriquePage() {
  const session = await auth();
  if (!session?.user?.id) redirect("/auth/login");
  const userId = session.user.id;

  const plan = (session.user as { plan?: string }).plan ?? "FREE";
  const cutoff = plan === "PREMIUM"
    ? undefined
    : new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);

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

  return (
    <HistoryClient
      readings={readings.map((r) => ({
        id: r.id,
        measuredAt: r.measuredAt.toISOString(),
        moment: r.moment,
        value: r.value,
        notes: r.notes,
      }))}
      isPremium={plan === "PREMIUM"}
    />
  );
}
