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 { data, error } = await supabase
    .from('rmp_io_extensions')
    .select('*, rmp_clients(company_name), rmp_products(name, product_type), rmp_orders(site)')
    .not('email_scheduled_date', 'is', null)
    .order('email_scheduled_date', { ascending: true });

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

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