import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { createExpenseSchema, expenseFilterSchema } from "@/lib/validations/expense";
import { Prisma, ExpenseStatus } from "@prisma/client";

// ─── Helper : récupérer l'organisation de l'utilisateur ──────
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;
}

function round2(n: number): number {
  return Math.round(n * 100) / 100;
}

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

  const { searchParams } = new URL(request.url);
  const rawParams = Object.fromEntries(searchParams.entries());
  const parsed = expenseFilterSchema.safeParse(rawParams);

  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: "Paramètres invalides", details: parsed.error.flatten() },
      { status: 422 }
    );
  }

  const { page, limit, categoryId, status, from, to, search } = parsed.data;

  const where: Prisma.ExpenseWhereInput = {
    organizationId: orgId,
    ...(categoryId && { categoryId }),
    ...(status && { status: status as ExpenseStatus }),
    ...(from || to
      ? {
          date: {
            ...(from && { gte: new Date(from) }),
            ...(to && { lte: new Date(to) }),
          },
        }
      : {}),
    ...(search && {
      OR: [
        { title: { contains: search, mode: "insensitive" } },
        { description: { contains: search, mode: "insensitive" } },
        { reference: { contains: search, mode: "insensitive" } },
        { supplier: { name: { contains: search, mode: "insensitive" } } },
      ],
    }),
  };

  const [expenses, total] = await prisma.$transaction([
    prisma.expense.findMany({
      where,
      include: {
        category: { select: { id: true, name: true, color: true, icon: true } },
        supplier: { select: { id: true, name: true } },
      },
      orderBy: { date: "desc" },
      skip: (page - 1) * limit,
      take: limit,
    }),
    prisma.expense.count({ where }),
  ]);

  // 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: orgId, date: { gte: startOfMonth } },
    _sum: { amount: true },
    _count: true,
  });

  return NextResponse.json({
    success: true,
    data: expenses,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit),
    },
    summary: {
      monthlyTotal: Number(monthlyAgg._sum.amount ?? 0),
      monthlyCount: monthlyAgg._count,
    },
  });
}

// ─── POST /api/expenses ───────────────────────────────────────
export async function POST(request: NextRequest) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;

  const body = await request.json().catch(() => null);
  if (!body) {
    return NextResponse.json({ success: false, error: "Corps de requête invalide" }, { status: 400 });
  }

  const parsed = createExpenseSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: "Données invalides", details: parsed.error.flatten() },
      { status: 422 }
    );
  }

  const data = parsed.data;

  // Vérifier que la catégorie appartient à l'organisation
  if (data.categoryId) {
    const cat = await prisma.expenseCategory.findFirst({
      where: { id: data.categoryId, organizationId: orgId },
    });
    if (!cat) {
      return NextResponse.json(
        { success: false, error: "Catégorie introuvable dans cette organisation" },
        { status: 404 }
      );
    }
  }

  // Vérifier que le fournisseur appartient à l'organisation
  if (data.supplierId) {
    const supplier = await prisma.supplier.findFirst({
      where: { id: data.supplierId, organizationId: orgId },
    });
    if (!supplier) {
      return NextResponse.json(
        { success: false, error: "Fournisseur introuvable dans cette organisation" },
        { status: 404 }
      );
    }
  }

  const taxAmount = round2(data.amount * (data.taxRate / 100));

  const expense = await prisma.expense.create({
    data: {
      organizationId: orgId,
      title: data.title,
      description: data.description ?? null,
      amount: data.amount,
      taxAmount,
      taxRate: data.taxRate,
      currency: data.currency,
      categoryId: data.categoryId ?? null,
      supplierId: data.supplierId ?? null,
      date: data.date ? new Date(data.date) : new Date(),
      paymentMethod: data.paymentMethod ?? null,
      reference: data.reference ?? null,
      notes: data.notes ?? null,
      isRecurring: data.isRecurring ?? false,
      recurringRule: data.recurringRule ?? null,
      status: "PENDING",
    },
    include: {
      category: { select: { id: true, name: true, color: true, icon: true } },
      supplier: { select: { id: true, name: true } },
    },
  });

  return NextResponse.json({ success: true, data: expense }, { status: 201 });
}
