import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { getClients, upsertClient } from '@/lib/billing/billingService';
import { moonCreateContact, moonUpdateContact } from '@/lib/billing/moonInvoiceClient';
import { getBillingMode } from '@/lib/billing/billingService';

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 });

  const { searchParams } = new URL(req.url);
  const companyId = searchParams.get('companyId') || undefined;

  try {
    const data = await getClients(companyId);
    return NextResponse.json({ data });
  } 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 { client, moonCompany } = body;
    const mode = getBillingMode();
    let moonContactId = client.mooninvoice_contact_id;

    if (mode === 'mooninvoice') {
      const mc = moonCompany || 'rmp';
      try {
        if (moonContactId) {
          await moonUpdateContact(mc, moonContactId, client);
        } else {
          const res = await moonCreateContact(mc, client);
          moonContactId = res?.contact_id || res?.id;
        }
      } catch {
        // Log but continue
      }
    }

    const saved = await upsertClient({ ...client, mooninvoice_contact_id: moonContactId });
    return NextResponse.json({ data: saved });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
