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 { searchParams } = new URL(request.url);
  const start = searchParams.get('start') ?? `${new Date().getFullYear()}-01-01`;
  const end = searchParams.get('end') ?? new Date().toISOString().split('T')[0];

  const [invoicesRes, expensesRes] = await Promise.all([
    supabase.from('rmp_invoices').select('site, amount_cents, client_id, rmp_clients(company_name)').eq('status', 'paid').gte('paid_date', start).lte('paid_date', end),
    supabase.from('rmp_expenses').select('category, amount_cents').gte('expense_date', start).lte('expense_date', end),
  ]);

  const invoices = invoicesRes.data ?? [];
  const expenses = expensesRes.data ?? [];

  const total_revenue_cents = invoices.reduce((s: number, i: any) => s + (i.amount_cents ?? 0), 0);
  const total_expenses_cents = expenses.reduce((s: number, e: any) => s + (e.amount_cents ?? 0), 0);

  // By site
  const siteMap: Record<string, number> = {};
  for (const inv of invoices) {
    siteMap[inv.site] = (siteMap[inv.site] ?? 0) + (inv.amount_cents ?? 0);
  }
  const by_site = Object.entries(siteMap).map(([site, revenue_cents]) => ({ site, revenue_cents })).sort((a, b) => b.revenue_cents - a.revenue_cents);

  // Top clients
  const clientMap: Record<string, any> = {};
  for (const inv of invoices) {
    if (!inv.client_id) continue;
    if (!clientMap[inv.client_id]) clientMap[inv.client_id] = { id: inv.client_id, company_name: (inv as any).rmp_clients?.company_name, revenue_cents: 0 };
    clientMap[inv.client_id].revenue_cents += inv.amount_cents ?? 0;
  }
  const top_clients = Object.values(clientMap).sort((a: any, b: any) => b.revenue_cents - a.revenue_cents).slice(0, 10);

  // By expense category
  const catMap: Record<string, number> = {};
  for (const exp of expenses) {
    catMap[exp.category ?? 'other'] = (catMap[exp.category ?? 'other'] ?? 0) + (exp.amount_cents ?? 0);
  }
  const by_category = Object.entries(catMap).map(([category, amount_cents]) => ({ category, amount_cents })).sort((a, b) => b.amount_cents - a.amount_cents);

  return NextResponse.json({ total_revenue_cents, total_expenses_cents, net_profit_cents: total_revenue_cents - total_expenses_cents, by_site, top_clients, by_category });
}
