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 now = new Date();
  const yearStart = `${now.getFullYear()}-01-01`;
  const monthStart = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`;

  // Revenue YTD (paid invoices)
  const { data: revenueYtd } = await supabase
    .from('rmp_invoices')
    .select('amount_cents')
    .eq('status', 'paid')
    .gte('paid_date', yearStart);

  const revenue_ytd = (revenueYtd ?? []).reduce((s: number, r: any) => s + (r.amount_cents ?? 0), 0);

  // Expenses YTD
  const { data: expensesYtd } = await supabase
    .from('rmp_expenses')
    .select('amount_cents')
    .gte('expense_date', yearStart);

  const expenses_ytd = (expensesYtd ?? []).reduce((s: number, r: any) => s + (r.amount_cents ?? 0), 0);

  // Outstanding invoices
  const { data: outstanding } = await supabase
    .from('rmp_invoices')
    .select('amount_cents')
    .in('status', ['pending', 'overdue']);

  const outstanding_total = (outstanding ?? []).reduce((s: number, r: any) => s + (r.amount_cents ?? 0), 0);

  // Unreconciled transactions
  const { count: unreconciled } = await supabase
    .from('rmp_bank_transactions')
    .select('*', { count: 'exact', head: true })
    .eq('reconciled', false);

  // Commissions outstanding
  const { data: commOutstanding } = await supabase
    .from('rmp_commissions')
    .select('commission_amount_cents')
    .eq('paid', false);

  const commissions_outstanding = (commOutstanding ?? []).reduce((s: number, r: any) => s + (r.commission_amount_cents ?? 0), 0);

  // Site revenue breakdown
  const { data: siteInvoices } = await supabase
    .from('rmp_invoices')
    .select('site, amount_cents, status, paid_date')
    .gte('created_at', yearStart);

  const sites = ['avbeat', 'avbeat', 'backlotbeat', 'broadcastengineering'];
  const siteRevenue = sites.map(site => {
    const siteData = (siteInvoices ?? []).filter((i: any) => i.site === site);
    const revenue_ytd = siteData.filter((i: any) => i.status === 'paid').reduce((s: number, r: any) => s + (r.amount_cents ?? 0), 0);
    const revenue_mtd = siteData.filter((i: any) => i.status === 'paid' && i.paid_date >= monthStart).reduce((s: number, r: any) => s + (r.amount_cents ?? 0), 0);
    const outstanding = siteData.filter((i: any) => ['pending', 'overdue'].includes(i.status)).reduce((s: number, r: any) => s + (r.amount_cents ?? 0), 0);
    return { site, revenue_ytd, revenue_mtd, outstanding, active_orders: 0 };
  });

  // Top clients
  const { data: clientInvoices } = await supabase
    .from('rmp_invoices')
    .select('client_id, amount_cents, rmp_clients(company_name)')
    .eq('status', 'paid')
    .gte('paid_date', yearStart);

  const clientMap: Record<string, any> = {};
  for (const inv of (clientInvoices ?? [])) {
    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_ytd: 0, active_orders: 0 };
    clientMap[inv.client_id].revenue_ytd += inv.amount_cents ?? 0;
  }
  const topClients = Object.values(clientMap).sort((a: any, b: any) => b.revenue_ytd - a.revenue_ytd).slice(0, 5);

  return NextResponse.json({
    stats: { revenue_ytd, expenses_ytd, net_profit: revenue_ytd - expenses_ytd, outstanding: outstanding_total, unreconciled: unreconciled ?? 0, commissions_outstanding },
    siteRevenue,
    topClients,
  });
}
