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 staff_id = searchParams.get('staff_id');

  let query = supabase
    .from('rmp_commissions')
    .select('*, rmp_sales_staff(full_name), rmp_invoices(invoice_number)')
    .eq('year', year)
    .order('created_at', { ascending: false });

  if (staff_id) query = query.eq('staff_id', staff_id);

  const { data, error } = await query;
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  return NextResponse.json({ commissions: data ?? [] });
}
