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 year = parseInt(searchParams.get('year') ?? String(new Date().getFullYear()));

  const { data: staff } = await supabase.from('rmp_sales_staff').select('id, full_name').eq('status', 'active');
  const { data: tiers } = await supabase.from('rmp_commission_tiers').select('*').eq('effective_year', year).order('tier_order');
  const { data: comms } = await supabase.from('rmp_commissions').select('*').eq('year', year);

  const summary = (staff ?? []).map((s: any) => {
    const staffComms = (comms ?? []).filter((c: any) => c.staff_id === s.id);
    const staffTiers = (tiers ?? []).filter((t: any) => t.staff_id === s.id);
    const ytd_sales_cents = staffComms.reduce((sum: number, c: any) => sum + (c.sale_amount_cents ?? 0), 0);
    const earned_cents = staffComms.reduce((sum: number, c: any) => sum + (c.commission_amount_cents ?? 0), 0);
    const outstanding_cents = staffComms.filter((c: any) => !c.paid).reduce((sum: number, c: any) => sum + (c.commission_amount_cents ?? 0), 0);

    // Find current tier
    let current_tier = 'Tier 1';
    let next_threshold_cents = null;
    for (const tier of staffTiers) {
      if (!tier.threshold_cents || ytd_sales_cents < tier.threshold_cents) {
        current_tier = `Tier ${tier.tier_order} (${(tier.rate * 100).toFixed(0)}%)`;
        next_threshold_cents = tier.threshold_cents;
        break;
      }
    }

    return { staff_id: s.id, full_name: s.full_name, ytd_sales_cents, earned_cents, outstanding_cents, current_tier, next_threshold_cents };
  });

  return NextResponse.json({ summary });
}
