/**
 * MoonInvoice API Client
 * Direct REST calls using stored env vars.
 * All reads go through local cache (billing tables).
 * Only writes and scheduled syncs hit the Moon API.
 */

const MOON_BASE_URL = 'https://api.mooninvoice.com/api_mi/public';

export type MoonCompany = 'rmp' | 'jtr';

function getApiKey(company: MoonCompany): string {
  const key =
    company === 'rmp'
      ? process.env.MOONINVOICE_API_KEY_RMP
      : process.env.MOONINVOICE_API_KEY_JTR;
  if (!key) throw new Error(`MoonInvoice API key not configured for ${company.toUpperCase()}`);
  return key;
}

async function moonFetch(
  company: MoonCompany,
  path: string,
  options: RequestInit = {}
): Promise<any> {
  const apiKey = getApiKey(company);
  const url = `${MOON_BASE_URL}${path}`;

  const res = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${apiKey}`,
      ...(options.headers || {}),
    },
  });

  if (!res.ok) {
    const text = await res.text().catch(() => '');
    throw new Error(`MoonInvoice API error ${res.status}: ${text}`);
  }

  return res.json();
}

// ─── Contacts ────────────────────────────────────────────────────────────────

export async function moonGetContacts(company: MoonCompany, page = 1): Promise<any> {
  return moonFetch(company, `/contact_list?page=${page}`);
}

export async function moonCreateContact(company: MoonCompany, data: Record<string, any>): Promise<any> {
  return moonFetch(company, '/add_contact', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

export async function moonUpdateContact(
  company: MoonCompany,
  contactId: string,
  data: Record<string, any>
): Promise<any> {
  return moonFetch(company, `/update_contact/${contactId}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
}

// ─── Invoices ────────────────────────────────────────────────────────────────

export async function moonGetInvoices(
  company: MoonCompany,
  page = 1,
  status?: string
): Promise<any> {
  const params = new URLSearchParams({ page: String(page) });
  if (status) params.set('status', status);
  return moonFetch(company, `/invoice_list?${params}`);
}

export async function moonGetInvoice(company: MoonCompany, invoiceId: string): Promise<any> {
  return moonFetch(company, `/invoice_detail/${invoiceId}`);
}

export async function moonCreateInvoice(
  company: MoonCompany,
  data: Record<string, any>
): Promise<any> {
  return moonFetch(company, '/add_invoice', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

export async function moonUpdateInvoice(
  company: MoonCompany,
  invoiceId: string,
  data: Record<string, any>
): Promise<any> {
  return moonFetch(company, `/update_invoice/${invoiceId}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
}

export async function moonSendInvoice(company: MoonCompany, invoiceId: string): Promise<any> {
  return moonFetch(company, `/send_invoice/${invoiceId}`, { method: 'POST' });
}

export async function moonRecordPayment(
  company: MoonCompany,
  invoiceId: string,
  data: Record<string, any>
): Promise<any> {
  return moonFetch(company, `/record_payment/${invoiceId}`, {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

export async function moonGetInvoicePdf(company: MoonCompany, invoiceId: string): Promise<Response> {
  const apiKey = getApiKey(company);
  return fetch(`${MOON_BASE_URL}/invoice_pdf/${invoiceId}`, {
    headers: { Authorization: `Bearer ${apiKey}` },
  });
}

export async function moonDeleteInvoice(company: MoonCompany, invoiceId: string): Promise<any> {
  return moonFetch(company, `/delete_invoice/${invoiceId}`, { method: 'DELETE' });
}

// ─── Payments ────────────────────────────────────────────────────────────────

export async function moonGetPayments(company: MoonCompany, page = 1): Promise<any> {
  return moonFetch(company, `/payment_list?page=${page}`);
}

// ─── Test connection ─────────────────────────────────────────────────────────

export async function moonTestConnection(company: MoonCompany): Promise<{ ok: boolean; message: string }> {
  try {
    await moonGetContacts(company, 1);
    return { ok: true, message: 'Connection successful' };
  } catch (err: any) {
    return { ok: false, message: err.message || 'Connection failed' };
  }
}
