import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { ExpenseListClient } from "@/components/expenses/expense-list-client";

async function getOrganization(userId: string) {
  const membership = await prisma.organizationMember.findFirst({
    where: { userId, joinedAt: { not: null } },
    include: { organization: true },
    orderBy: { createdAt: "asc" },
  });
  return membership?.organization ?? null;
}

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

  const org = await getOrganization(session.user.id);
  if (!org) redirect("/onboarding");

  // Chargement initial des dépenses (page 1)
  const [expenses, total, categories] = await prisma.$transaction([
    prisma.expense.findMany({
      where: { organizationId: org.id },
      include: {
        category: { select: { id: true, name: true, color: true, icon: true } },
        supplier: { select: { id: true, name: true } },
      },
      orderBy: { date: "desc" },
      take: 20,
    }),
    prisma.expense.count({ where: { organizationId: org.id } }),
    prisma.expenseCategory.findMany({
      where: { organizationId: org.id },
      orderBy: [{ isDefault: "desc" }, { name: "asc" }],
    }),
  ]);

  // Résumé du mois courant
  const now = new Date();
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthlyAgg = await prisma.expense.aggregate({
    where: { organizationId: org.id, date: { gte: startOfMonth } },
    _sum: { amount: true },
    _count: true,
  });

  return (
    <ExpenseListClient
      initialExpenses={expenses.map((e) => ({
        ...e,
        amount: Number(e.amount),
        taxAmount: Number(e.taxAmount),
        taxRate: Number(e.taxRate),
      }))}
      initialTotal={total}
      categories={categories}
      monthlyTotal={Number(monthlyAgg._sum.amount ?? 0)}
      monthlyCount={monthlyAgg._count}
    />
  );
}
