import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { updateExpenseSchema } from "@/lib/validations/expense";

// ─── 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/[id] ───────────────────────────────────
export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;

  const { id } = await params;

  const expense = await prisma.expense.findFirst({
    where: { id, organizationId: orgId },
    include: {
      category: true,
      supplier: { select: { id: true, name: true, email: true } },
      documents: true,
    },
  });

  if (!expense) {
    return NextResponse.json({ success: false, error: "Dépense introuvable" }, { status: 404 });
  }

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

// ─── PATCH /api/expenses/[id] ─────────────────────────────────
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;

  const { id } = await params;

  const existing = await prisma.expense.findFirst({
    where: { id, organizationId: orgId },
  });
  if (!existing) {
    return NextResponse.json({ success: false, error: "Dépense introuvable" }, { status: 404 });
  }

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

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

  const data = parsed.data;

  // Recalculer taxAmount si amount ou taxRate changent
  const newAmount = data.amount ?? Number(existing.amount);
  const newTaxRate = data.taxRate ?? Number(existing.taxRate);
  const taxAmount = round2(newAmount * (newTaxRate / 100));

  const updated = await prisma.expense.update({
    where: { id },
    data: {
      ...(data.title !== undefined && { title: data.title }),
      ...(data.description !== undefined && { description: data.description }),
      ...(data.amount !== undefined && { amount: data.amount }),
      ...(data.taxRate !== undefined && { taxRate: data.taxRate }),
      taxAmount,
      ...(data.currency !== undefined && { currency: data.currency }),
      ...(data.categoryId !== undefined && { categoryId: data.categoryId }),
      ...(data.supplierId !== undefined && { supplierId: data.supplierId }),
      ...(data.date !== undefined && { date: new Date(data.date) }),
      ...(data.paymentMethod !== undefined && { paymentMethod: data.paymentMethod }),
      ...(data.reference !== undefined && { reference: data.reference }),
      ...(data.notes !== undefined && { notes: data.notes }),
      ...(data.isRecurring !== undefined && { isRecurring: data.isRecurring }),
      ...(data.recurringRule !== undefined && { recurringRule: data.recurringRule }),
    },
    include: {
      category: { select: { id: true, name: true, color: true, icon: true } },
      supplier: { select: { id: true, name: true } },
    },
  });

  return NextResponse.json({ success: true, data: updated });
}

// ─── DELETE /api/expenses/[id] ────────────────────────────────
export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;

  const { id } = await params;

  const existing = await prisma.expense.findFirst({
    where: { id, organizationId: orgId },
  });
  if (!existing) {
    return NextResponse.json({ success: false, error: "Dépense introuvable" }, { status: 404 });
  }

  await prisma.expense.delete({ where: { id } });

  return NextResponse.json({ success: true, data: { id } });
}
