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

async function getOrgId(userId: string) {
}

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

  const { searchParams } = new URL(req.url);
  const type = searchParams.get("type") ?? "income-statement";
  const year = parseInt(searchParams.get("year") ?? String(new Date().getFullYear()));

  const startDate = new Date(year, 0, 1);
  const endDate = new Date(year, 11, 31, 23, 59, 59);

  switch (type) {
    case "income-statement": {
      const [revenues, expenses] = await Promise.all([
        prisma.invoice.aggregate({
          where: { organizationId: orgId, status: "PAID", paidDate: { gte: startDate, lte: endDate } },
          _sum: { total: true, taxAmount: true, subtotal: true },
        }),
        prisma.expense.aggregate({
          where: { organizationId: orgId, status: { in: ["APPROVED", "REIMBURSED"] }, date: { gte: startDate, lte: endDate } },
          _sum: { amount: true, taxAmount: true },
        }),
      ]);

      const totalRevenue = Number(revenues._sum.total ?? 0);
      const totalExpenses = Number(expenses._sum.amount ?? 0);

      // Revenus mensuels
      const monthlyRevenues = await prisma.$queryRaw<Array<{ month: number; total: number }>>`
        SELECT EXTRACT(MONTH FROM "paidDate")::int as month, SUM(total)::float as total
        FROM "Invoice"
        WHERE "organizationId" = ${orgId} AND status = 'PAID'
          AND "paidDate" BETWEEN ${startDate} AND ${endDate}
        GROUP BY month ORDER BY month
      `;

      const monthlyExpenses = await prisma.$queryRaw<Array<{ month: number; total: number }>>`
        SELECT EXTRACT(MONTH FROM date)::int as month, SUM(amount)::float as total
        FROM "Expense"
        WHERE "organizationId" = ${orgId} AND status IN ('APPROVED', 'REIMBURSED')
          AND date BETWEEN ${startDate} AND ${endDate}
        GROUP BY month ORDER BY month
      `;

      return NextResponse.json({
        success: true,
        data: {
          type: "income-statement",
          year,
          totalRevenue,
          totalExpenses,
          netProfit: totalRevenue - totalExpenses,
          grossMargin: totalRevenue > 0 ? ((totalRevenue - totalExpenses) / totalRevenue) * 100 : 0,
          revenueHT: Number(revenues._sum.subtotal ?? 0),
          revenueTax: Number(revenues._sum.taxAmount ?? 0),
          expensesHT: totalExpenses - Number(expenses._sum.taxAmount ?? 0),
          expensesTax: Number(expenses._sum.taxAmount ?? 0),
          monthlyRevenues,
          monthlyExpenses,
        },
      });
    }

    case "balance-sheet": {
      const [bankBalance, pendingReceivables, pendingPayables] = await Promise.all([
        prisma.bankAccount.aggregate({
          where: { organizationId: orgId, isActive: true },
          _sum: { balance: true },
        }),
        prisma.invoice.aggregate({
          where: { organizationId: orgId, status: { in: ["SENT", "OVERDUE"] } },
          _sum: { amountDue: true },
        }),
        prisma.expense.aggregate({
          where: { organizationId: orgId, status: "PENDING" },
          _sum: { amount: true },
        }),
      ]);

      return NextResponse.json({
        success: true,
        data: {
          type: "balance-sheet",
          year,
          assets: {
            cash: Number(bankBalance._sum.balance ?? 0),
            receivables: Number(pendingReceivables._sum.amountDue ?? 0),
          },
          liabilities: {
            payables: Number(pendingPayables._sum.amount ?? 0),
          },
        },
      });
    }

    case "vat": {
      const [collected, deductible] = await Promise.all([
        prisma.invoice.aggregate({
          where: { organizationId: orgId, status: "PAID", paidDate: { gte: startDate, lte: endDate } },
          _sum: { taxAmount: true },
        }),
        prisma.expense.aggregate({
          where: { organizationId: orgId, status: { in: ["APPROVED", "REIMBURSED"] }, date: { gte: startDate, lte: endDate } },
          _sum: { taxAmount: true },
        }),
      ]);

      const vatCollected = Number(collected._sum.taxAmount ?? 0);
      const vatDeductible = Number(deductible._sum.taxAmount ?? 0);

      return NextResponse.json({
        success: true,
        data: {
          type: "vat",
          year,
          vatCollected,
          vatDeductible,
          vatDue: vatCollected - vatDeductible,
        },
      });
    }

    default:
      return NextResponse.json({ success: false, error: "Type de rapport invalide" }, { status: 400 });
  }
}
