import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { requireAdopsAccess } from '@/lib/accounting/rmpService';

export async function GET(request: NextRequest) {
  const auth = await requireAdopsAccess();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const supabase = await createClient();
  const { searchParams } = new URL(request.url);
  const status = searchParams.get('status');
  const site = searchParams.get('site');

  let query = supabase
    .from('rmp_io_extensions')
    .select('*, rmp_clients(company_name), rmp_products(name), rmp_sales_staff(full_name), rmp_orders(site)')
    .in('flight_status', ['active', 'scheduled'])
    .order('start_date', { ascending: false });

  if (status) query = query.eq('flight_status', status);

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

  let filtered = data ?? [];
  if (site) filtered = filtered.filter((io: any) => io.rmp_orders?.site === site);

  return NextResponse.json({ flights: filtered });
}
