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, product_type, dimensions), rmp_sales_staff(full_name), rmp_orders(site)')
    .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 });

  // Filter by site via joined order
  let filtered = data ?? [];
  if (site) filtered = filtered.filter((io: any) => io.rmp_orders?.site === site);

  // Hide pricing for adops_uploader
  if (auth.role === 'adops_uploader') {
    filtered = filtered.map((io: any) => {
      const { is_paid, ...rest } = io;
      return rest;
    });
  }

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

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

  const supabase = await createClient();
  const body = await request.json();

  const { data, error } = await supabase.from('rmp_io_extensions').insert({
    existing_io_id: body.existing_io_id,
    order_id: body.order_id || null,
    product_id: body.product_id || null,
    staff_id: body.staff_id || null,
    client_id: body.client_id || null,
    is_comp: body.is_comp ?? false,
    comp_reason: body.comp_reason || null,
    is_paid: body.is_paid ?? false,
    flight_status: body.flight_status ?? 'scheduled',
    start_date: body.start_date,
    end_date: body.end_date || null,
    auto_deactivate: body.auto_deactivate ?? true,
    banner_image_url: body.banner_image_url || null,
    click_through_url: body.click_through_url || null,
    alt_text: body.alt_text || null,
    email_html_url: body.email_html_url || null,
    email_scheduled_date: body.email_scheduled_date || null,
    email_list_segment: body.email_list_segment || null,
    page_url: body.page_url || null,
    newsletter_issue_date: body.newsletter_issue_date || null,
    notes: body.notes || null,
  }).select().single();

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