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

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

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

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

  return NextResponse.json({ invoices: 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 invoice_number = await generateInvoiceNumber();

  const { data, error } = await supabase.from('rmp_invoices').insert({
    order_id: body.order_id || null,
    client_id: body.client_id || null,
    staff_id: body.staff_id || null,
    invoice_number,
    site: body.site,
    amount_cents: body.amount_cents,
    currency: body.currency ?? 'USD',
    status: 'pending',
    issue_date: body.issue_date || new Date().toISOString().split('T')[0],
    due_date: body.due_date || null,
    is_staff_sale: body.is_staff_sale ?? false,
    notes: body.notes || null,
  }).select().single();

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