import { NextRequest, NextResponse } from "next/server"; import { queryRaw } from "@/lib/db"; import { getCurrentUser } from "@/lib/auth"; interface BalanceRow { participant_id: number; name: string; total_owed: number; transaction_count: number; } export async function GET( req: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const user = await getCurrentUser(req); if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); const { id } = await params; const rows = await queryRaw( `SELECT ts.participant_id, p.name, SUM(COALESCE(t.amount_aud, t.amount) * ts.share_percent / 100)::numeric(12,2) as total_owed, COUNT(*)::int as transaction_count FROM transaction_splits ts JOIN transactions t ON t.id = ts.transaction_id JOIN participants p ON p.id = ts.participant_id WHERE ts.participant_id = $1 AND ts.settled = false GROUP BY ts.participant_id, p.name`, [Number(id)] ); return NextResponse.json( rows[0] ?? { participant_id: Number(id), total_owed: 0, transaction_count: 0 } ); }