import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { getInvoices, upsertInvoice, updateInvoiceStatus } from '@/lib/billing/billingService';
import { moonCreateInvoice, moonSendInvoice, moonRecordPayment, moonDeleteInvoice } 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 filters = {
    companyId: searchParams.get('companyId') || undefined,
    status: searchParams.get('status') || undefined,
    clientId: searchParams.get('clientId') || undefined,
    dateFrom: searchParams.get('dateFrom') || undefined,
    dateTo: searchParams.get('dateTo') || undefined,
    search: searchParams.get('search') || undefined,
  };

  try {
    const data = await getInvoices(filters);
    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 { invoice, lineItems, action, invoiceId, company } = body;

    // Handle actions on existing invoices
    if (action && invoiceId) {
      const mode = getBillingMode();
      const moonCompany = company === 'jtr' ? 'jtr' : 'rmp';

      if (action === 'send') {
        if (mode === 'mooninvoice') {
          const inv = await getInvoices({ search: invoiceId });
          const moonId = inv?.[0]?.mooninvoice_invoice_id;
          if (moonId) await moonSendInvoice(moonCompany, moonId);
        }
        await updateInvoiceStatus(invoiceId, 'sent');
        return NextResponse.json({ ok: true });
      }

      if (action === 'record_payment') {
        const { amount, paymentDate, method } = body;
        if (mode === 'mooninvoice') {
          const inv = await getInvoices({ search: invoiceId });
          const moonId = inv?.[0]?.mooninvoice_invoice_id;
          if (moonId) await moonRecordPayment(moonCompany, moonId, { amount, payment_date: paymentDate, method });
        }
        await updateInvoiceStatus(invoiceId, 'paid');
        return NextResponse.json({ ok: true });
      }

      if (action === 'cancel') {
        if (mode === 'mooninvoice') {
          const inv = await getInvoices({ search: invoiceId });
          const moonId = inv?.[0]?.mooninvoice_invoice_id;
          if (moonId) await moonDeleteInvoice(moonCompany, moonId);
        }
        await updateInvoiceStatus(invoiceId, 'cancelled');
        return NextResponse.json({ ok: true });
      }
    }

    // Create new invoice
    const mode = getBillingMode();
    let moonInvoiceId: string | undefined;

    if (mode === 'mooninvoice' && invoice) {
      const moonCompany = invoice.moonCompany || 'rmp';
      try {
        const moonRes = await moonCreateInvoice(moonCompany, {
          ...invoice,
          line_items: lineItems,
        });
        moonInvoiceId = moonRes?.invoice_id || moonRes?.id;
      } catch {
        // Log but don't fail — save to local cache anyway
      }
    }

    const saved = await upsertInvoice(
      { ...invoice, mooninvoice_invoice_id: moonInvoiceId },
      lineItems
    );
    return NextResponse.json({ data: saved });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
