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

  let query = supabase.from('rmp_expenses').select('*').order('expense_date', { ascending: false });
  if (category) query = query.eq('category', category);
  if (reconciled !== null && reconciled !== '') query = query.eq('reconciled', reconciled === 'true');

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

  return NextResponse.json({ expenses: 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 { data, error } = await supabase.from('rmp_expenses').insert({
    vendor: body.vendor || null,
    amount_cents: body.amount_cents,
    currency: body.currency ?? 'USD',
    category: body.category,
    description: body.description || null,
    expense_date: body.expense_date,
    receipt_source: body.receipt_source ?? 'manual',
    reconciled: false,
  }).select().single();

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