import { NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { forecastCashflow } from "@/lib/ai";

export async function GET() {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { orgId } = ctx;

  // Collect last 6 months of revenue and expenses
  const now = new Date();
  const monthlyRevenues: number[] = [];
  const monthlyExpenses: number[] = [];

  for (let i = 5; i >= 0; i--) {
    const start = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const end = new Date(now.getFullYear(), now.getMonth() - i + 1, 0, 23, 59, 59);

    const [rev, exp] = await Promise.all([
      prisma.invoice.aggregate({
        where: { organizationId: orgId, status: "PAID", paidDate: { gte: start, lte: end } },
        _sum: { total: true },
      }),
      prisma.expense.aggregate({
        where: { organizationId: orgId, status: "APPROVED", date: { gte: start, lte: end } },
        _sum: { amount: true },
      }),
    ]);

    monthlyRevenues.push(Number(rev._sum.total ?? 0));
    monthlyExpenses.push(Number(exp._sum.amount ?? 0));
  }

  const bankBalance = await prisma.bankAccount.aggregate({
    where: { organizationId: orgId, isActive: true },
    _sum: { balance: true },
  });

  const currentBalance = Number(bankBalance._sum.balance ?? 0);

  try {
    const forecast = await forecastCashflow({ monthlyRevenues, monthlyExpenses, currentBalance });
    return NextResponse.json({
      success: true,
      data: { forecast, monthlyRevenues, monthlyExpenses, currentBalance },
    });
  } catch {
    return NextResponse.json({ success: false, error: "Impossible de générer les prévisions" }, { status: 500 });
  }
}
