import axios, { type AxiosRequestConfig } from 'axios';

function fineractAuthHeaders(): { base: string; headers: Record<string, string> } {
  const base = (process.env.OMNL_FINERACT_BASE_URL || '').replace(/\/$/, '');
  const tenant = process.env.OMNL_FINERACT_TENANT || 'omnl';
  const user =
    process.env.OMNL_FINERACT_USER?.trim() ||
    process.env.OMNL_FINERACT_USERNAME?.trim() ||
    'app.omnl';
  const pass = process.env.OMNL_FINERACT_PASSWORD || '';
  if (!base || !pass) {
    throw new Error('OMNL_FINERACT_BASE_URL and OMNL_FINERACT_PASSWORD required');
  }
  const auth = Buffer.from(`${user}:${pass}`).toString('base64');
  return {
    base,
    headers: {
      Authorization: `Basic ${auth}`,
      'Fineract-Platform-TenantId': tenant,
      'Content-Type': 'application/json',
    },
  };
}

export async function fineractJournalExistsByReference(referenceNumber: string): Promise<boolean> {
  const { base, headers } = fineractAuthHeaders();
  const url = `${base}/journalentries`;
  const cfg: AxiosRequestConfig = {
    headers,
    timeout: 60000,
    params: { referenceNumber, limit: 1 },
  };
  try {
    const { data } = await axios.get(url, cfg);
    if (Array.isArray(data)) return data.length > 0;
    const items = (data as { pageItems?: unknown[] })?.pageItems;
    return Array.isArray(items) && items.length > 0;
  } catch {
    return false;
  }
}

export async function fineractOfficeHasClosureOnOrBefore(officeId: number, dateIso: string): Promise<boolean> {
  const { base, headers } = fineractAuthHeaders();
  const url = `${base}/glclosures`;
  const { data } = await axios.get(url, { headers, params: { officeId }, timeout: 60000 });
  const rows = Array.isArray(data) ? data : [];
  const target = new Date(dateIso).getTime();
  return rows.some((r: { closingDate?: string[] | string }) => {
    const raw = Array.isArray(r.closingDate) ? r.closingDate.join('-') : r.closingDate;
    if (!raw) return false;
    return new Date(raw).getTime() >= target;
  });
}

export async function fetchLatestJournalEntryId(officeId?: number): Promise<string | null> {
  const { base, headers } = fineractAuthHeaders();
  const params: Record<string, string | number> = { limit: 1, orderBy: 'id', sortOrder: 'DESC' };
  if (officeId) params.officeId = officeId;
  const { data } = await axios.get(`${base}/journalentries`, { headers, params, timeout: 60000 });
  const row = Array.isArray(data) ? data[0] : (data as { pageItems?: { id?: number }[] })?.pageItems?.[0];
  if (!row?.id) return null;
  return String(row.id);
}
