import { NextRequest, NextResponse } from "next/server"; import { revalidatePath } from "next/cache"; import { prisma } from "@/lib/prisma"; import { requireAuth } from "@/lib/auth-utils"; export async function POST(request: NextRequest) { const authError = await requireAuth(); if (authError) return authError; try { const { sourceAccountId, targetAccountId } = await request.json(); if (!sourceAccountId || !targetAccountId) { return NextResponse.json( { error: "Source and target account IDs are required" }, { status: 400 }, ); } if (sourceAccountId === targetAccountId) { return NextResponse.json( { error: "Source and target accounts must be different" }, { status: 400 }, ); } // Vérifier que les comptes existent const [sourceAccount, targetAccount] = await Promise.all([ prisma.account.findUnique({ where: { id: sourceAccountId }, include: { transactions: { select: { id: true, }, }, }, }), prisma.account.findUnique({ where: { id: targetAccountId }, }), ]); if (!sourceAccount || !targetAccount) { return NextResponse.json( { error: "One or both accounts not found" }, { status: 404 }, ); } const transactionCount = sourceAccount.transactions.length; // Déplacer toutes les transactions vers le compte cible await prisma.transaction.updateMany({ where: { accountId: sourceAccountId, }, data: { accountId: targetAccountId, }, }); // Recalculer le solde du compte cible à partir de toutes ses transactions const allTransactions = await prisma.transaction.findMany({ where: { accountId: targetAccountId, }, select: { amount: true, }, }); const calculatedBalance = allTransactions.reduce( (sum, t) => sum + t.amount, 0, ); // Calculer l'initialBalance total (somme des deux comptes) const totalInitialBalance = sourceAccount.initialBalance + targetAccount.initialBalance; // Mettre à jour le compte cible await prisma.account.update({ where: { id: targetAccountId, }, data: { balance: calculatedBalance, initialBalance: totalInitialBalance, // Garder le bankId du compte cible (celui qui est conservé) // Garder le dernier import le plus récent lastImport: sourceAccount.lastImport && targetAccount.lastImport ? sourceAccount.lastImport > targetAccount.lastImport ? sourceAccount.lastImport : targetAccount.lastImport : sourceAccount.lastImport || targetAccount.lastImport, }, }); // Supprimer le compte source await prisma.account.delete({ where: { id: sourceAccountId, }, }); // Revalider les caches revalidatePath("/accounts", "page"); revalidatePath("/transactions", "page"); revalidatePath("/statistics", "page"); revalidatePath("/dashboard", "page"); return NextResponse.json({ success: true, message: `Fusion réussie : ${transactionCount} transactions déplacées`, targetAccountId, transactionCount, calculatedBalance, }); } catch (error) { console.error("Error merging accounts:", error); return NextResponse.json( { error: "Failed to merge accounts" }, { status: 500 }, ); } }