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: staff, error } = await supabase
    .from('rmp_sales_staff')
    .select('*')
    .order('full_name');

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

  // Attach YTD commission data
  const year = new Date().getFullYear();
  const enriched = await Promise.all((staff ?? []).map(async (s: any) => {
    const { data: comms } = await supabase
      .from('rmp_commissions')
      .select('commission_amount_cents, paid')
      .eq('staff_id', s.id)
      .eq('year', year);

    const commission_ytd = (comms ?? []).reduce((sum: number, c: any) => sum + (c.commission_amount_cents ?? 0), 0);
    const commission_outstanding = (comms ?? []).filter((c: any) => !c.paid).reduce((sum: number, c: any) => sum + (c.commission_amount_cents ?? 0), 0);
    return { ...s, commission_ytd, commission_outstanding };
  }));

  return NextResponse.json({ staff: enriched });
}

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 { data: staffMember, error } = await supabase.from('rmp_sales_staff').insert({
    full_name: body.full_name,
    email: body.email || null,
    phone: body.phone || null,
    notes: body.notes || null,
    status: 'active',
  }).select().single();

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

  // Insert commission tiers
  if (body.tiers?.length > 0) {
    await supabase.from('rmp_commission_tiers').insert(
      body.tiers.map((t: any) => ({
        staff_id: staffMember.id,
        effective_year: t.effective_year,
        tier_order: t.tier_order,
        threshold_cents: t.threshold_cents,
        rate: t.rate,
      }))
    );
  }

  return NextResponse.json({ staff: staffMember });
}
