import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { getBillingSettings, updateBillingSettings, getCompanies, updateCompany } from '@/lib/billing/billingService';
import { moonTestConnection } from '@/lib/billing/moonInvoiceClient';

async function requireAdmin(req: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return null;
  const { data: profile } = await supabase
    .from('user_profiles')
    .select('role')
    .eq('id', user.id)
    .single();
  if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
  return user;
}

export async function GET(req: NextRequest) {
  const admin = await requireAdmin(req);
  if (!admin) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  try {
    const [settings, companies] = await Promise.all([getBillingSettings(), getCompanies()]);
    return NextResponse.json({ settings, companies });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  const admin = await requireAdmin(req);
  if (!admin) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  try {
    const body = await req.json();
    const { action, settings, company, companyId } = body;

    if (action === 'test_connection') {
      const mc = company === 'jtr' ? 'jtr' : 'rmp';
      const result = await moonTestConnection(mc);
      return NextResponse.json(result);
    }

    if (action === 'update_company' && companyId) {
      const updated = await updateCompany(companyId, company);
      return NextResponse.json({ data: updated });
    }

    if (settings) {
      const updated = await updateBillingSettings(settings);
      return NextResponse.json({ data: updated });
    }

    return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
