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

async function getOrgId(userId: string) {
}

// ─── GET /api/bank/[id] ────────────────────────────────────────

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

  const { id } = await params;
  const account = await prisma.bankAccount.findFirst({
    where: { id, organizationId: orgId },
    include: {
      transactions: { orderBy: { date: "desc" }, take: 20 },
      _count: { select: { transactions: true } },
    },
  });

  if (!account) return NextResponse.json({ success: false, error: "Compte introuvable" }, { status: 404 });
  return NextResponse.json({ success: true, data: account });
}

// ─── PATCH /api/bank/[id] ──────────────────────────────────────

export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

  const { id } = await params;
  const existing = await prisma.bankAccount.findFirst({ where: { id, organizationId: orgId } });
  if (!existing) return NextResponse.json({ success: false, error: "Introuvable" }, { status: 404 });

  const body = await req.json().catch(() => ({}));
  const { name, bankName, iban, bic, currency, balance } = body;

  const updated = await prisma.bankAccount.update({
    where: { id },
    data: {
      ...(name !== undefined && { name }),
      ...(bankName !== undefined && { bankName }),
      ...(iban !== undefined && { iban }),
      ...(bic !== undefined && { bic }),
      ...(currency !== undefined && { currency }),
      ...(balance !== undefined && { balance }),
    },
  });

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

// ─── DELETE /api/bank/[id] ─────────────────────────────────────

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

  const { id } = await params;
  const existing = await prisma.bankAccount.findFirst({ where: { id, organizationId: orgId } });
  if (!existing) return NextResponse.json({ success: false, error: "Introuvable" }, { status: 404 });

  // Désactiver plutôt que supprimer pour préserver l'historique
  await prisma.bankAccount.update({ where: { id }, data: { isActive: false } });
  return NextResponse.json({ success: true });
}
