import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { requireRmpAdmin } from '@/lib/accounting/rmpService';

export async function GET(request: NextRequest) {
  const auth = await requireRmpAdmin();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const supabase = await createClient();
  const { data: transactions, error } = await supabase
    .from('rmp_bank_transactions')
    .select('*')
    .order('transaction_date', { ascending: false })
    .limit(200);

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  let matched = (transactions ?? []).filter((t: any) => t.reconciled).length;
  let unmatched = (transactions ?? []).filter((t: any) => !t.reconciled).length;

  return NextResponse.json({ transactions: transactions ?? [], summary: { matched, unmatched } });
}

export async function POST(request: NextRequest) {
  const auth = await requireRmpAdmin();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const supabase = await createClient();
  const body = await request.json();
  const csv: string = body.csv ?? '';

  const lines = csv.split('\n').filter(Boolean);
  const headers = lines[0]?.split(',').map((h: string) => h.trim().toLowerCase().replace(/"/g, '')) ?? [];

  const rows = lines.slice(1).map((line: string) => {
    const vals = line.split(',').map((v: string) => v.trim().replace(/"/g, ''));
    const row: Record<string, string> = {};
    headers.forEach((h: string, i: number) => { row[h] = vals[i] ?? ''; });
    return row;
  });

  let matched = 0;
  let unmatched = 0;

  for (const row of rows) {
    const date = row['date'] || row['transaction date'] || row['trans date'];
    const desc = row['description'] || row['memo'] || row['payee'];
    const amountStr = row['amount'] || row['debit'] || row['credit'];
    const amount = parseFloat(amountStr?.replace(/[$,]/g, '') ?? '0');
    if (!date || isNaN(amount)) continue;

    const amount_cents = Math.round(Math.abs(amount) * 100);
    const type = amount >= 0 ? 'credit' : 'debit';

    // Try to auto-match to invoice
    let matched_invoice_id = null;
    if (type === 'credit') {
      const { data: invoices } = await supabase
        .from('rmp_invoices')
        .select('id')
        .eq('amount_cents', amount_cents)
        .eq('status', 'pending')
        .gte('due_date', new Date(new Date(date).getTime() - 3 * 86400000).toISOString().split('T')[0])
        .lte('due_date', new Date(new Date(date).getTime() + 3 * 86400000).toISOString().split('T')[0])
        .limit(1);

      if (invoices?.[0]) {
        matched_invoice_id = invoices[0].id;
        matched++;
      } else {
        unmatched++;
      }
    }

    await supabase.from('rmp_bank_transactions').insert({
      transaction_date: date,
      description: desc,
      amount_cents: type === 'debit' ? -amount_cents : amount_cents,
      type,
      matched_invoice_id,
      reconciled: !!matched_invoice_id,
      raw_csv_row: row,
    });

    // If matched, mark invoice paid
    if (matched_invoice_id) {
      await supabase.from('rmp_invoices').update({ status: 'paid', paid_date: date, payment_method: 'wire' }).eq('id', matched_invoice_id);
    }
  }

  return NextResponse.json({ ok: true, summary: { matched, unmatched } });
}
