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

async function getOrgId(userId: string) {
}

// GET transactions d'un compte
export async function GET(req: Request, { 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 account = await prisma.bankAccount.findFirst({ where: { id, organizationId: orgId ?? "" } });
  if (!account) return NextResponse.json({ success: false, error: "Compte introuvable" }, { status: 404 });

  const { searchParams } = new URL(req.url);
  const page = Math.max(1, parseInt(searchParams.get("page") ?? "1"));
  const limit = Math.min(100, parseInt(searchParams.get("limit") ?? "30"));

  const [data, total] = await Promise.all([
    prisma.bankTransaction.findMany({
      where: { bankAccountId: id },
      orderBy: { date: "desc" },
      skip: (page - 1) * limit,
      take: limit,
    }),
    prisma.bankTransaction.count({ where: { bankAccountId: id } }),
  ]);

  return NextResponse.json({ success: true, data, total, page, limit, totalPages: Math.ceil(total / limit) });
}

// POST import CSV bancaire
export async function POST(req: Request, { 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 account = await prisma.bankAccount.findFirst({ where: { id, organizationId: orgId ?? "" } });
  if (!account) return NextResponse.json({ success: false, error: "Compte introuvable" }, { status: 404 });

  const formData = await req.formData();
  const file = formData.get("file") as File;
  if (!file) return NextResponse.json({ success: false, error: "Fichier manquant" }, { status: 400 });

  const text = await file.text();
  const { data } = Papa.parse(text, { header: true, skipEmptyLines: true });

  const transactions = (data as any[]).map((row) => {
    const amount = parseFloat(row.amount ?? row.montant ?? row.Amount ?? 0);
    return {
      bankAccountId: id,
      date: new Date(row.date ?? row.Date ?? new Date()),
      description: row.description ?? row.libelle ?? row.Description ?? "",
      amount: Math.abs(amount),
      type: amount >= 0 ? "INCOME" : "EXPENSE" as any,
      reference: row.reference ?? row.Reference ?? null,
      rawData: row,
    };
  });

  const created = await prisma.bankTransaction.createMany({ data: transactions });

  return NextResponse.json({ success: true, data: { imported: created.count } });
}
