import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { requireRmpAdmin, generateOrderNumber } 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 site = searchParams.get('site');
  const status = searchParams.get('status');
  const client = searchParams.get('client');

  let query = supabase
    .from('rmp_orders')
    .select('*, rmp_clients(company_name), rmp_products(name), rmp_sales_staff(full_name)')
    .order('created_at', { ascending: false });

  if (site) query = query.eq('site', site);
  if (status) query = query.eq('status', status);
  if (client) query = query.ilike('rmp_clients.company_name', `%${client}%`);

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

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

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 internal_order_number = await generateOrderNumber();

  const { data, error } = await supabase.from('rmp_orders').insert({
    client_id: body.client_id || null,
    staff_id: body.staff_id || null,
    po_number: body.po_number || null,
    internal_order_number,
    site: body.site,
    product_id: body.product_id || null,
    ad_unit: body.ad_unit || null,
    description: body.description || null,
    start_date: body.start_date || null,
    end_date: body.end_date || null,
    total_amount_cents: body.total_amount_cents || null,
    currency: body.currency ?? 'USD',
    invoicing_schedule: body.invoicing_schedule ?? 'single',
    next_invoice_date: body.next_invoice_date || null,
    notes: body.notes || null,
    status: 'active',
  }).select().single();

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