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 site = searchParams.get('site');

  let query = supabase.from('rmp_products').select('*').order('site').order('sort_order');
  if (site) query = query.eq('site', site);

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

  return NextResponse.json({ products: 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_products').insert({
    site: body.site,
    product_type: body.product_type,
    name: body.name,
    description: body.description || null,
    dimensions: body.dimensions || null,
    duration_days: body.duration_days || null,
    sort_order: body.sort_order ?? 0,
    active: true,
  }).select().single();

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