#!/usr/bin/env node
/**
 * Post Office 24 opening M1 journal to Fineract:
 *   Dr 1410 Due From Head Office
 *   Cr 2100 M1 Central Liabilities
 */
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '../..');
const configPath = path.join(repoRoot, 'config/offices/office-24-opening-journal.v1.json');

const dryRun = process.argv.includes('--dry-run');
const cfg = JSON.parse(fs.readFileSync(configPath, 'utf8'));

const base = (process.env.OMNL_FINERACT_BASE_URL || process.env.FINERACT_BASE_URL || '').replace(/\/$/, '');
const tenant = process.env.OMNL_FINERACT_TENANT || process.env.FINERACT_TENANT || 'omnl';
const user =
  process.env.OMNL_FINERACT_USER?.trim() ||
  process.env.OMNL_FINERACT_USERNAME?.trim() ||
  'ali_hospitallers_tenant';
const pass = process.env.OMNL_FINERACT_PASSWORD || '';
const amountRaw = process.env[cfg.amountEnv] || process.env.OFFICE24_OPENING_M1_USD || '';
const amount = parseFloat(amountRaw);

if (!base || !pass) {
  console.error('Set OMNL_FINERACT_BASE_URL and OMNL_FINERACT_PASSWORD');
  process.exit(1);
}
if (!Number.isFinite(amount) || amount <= 0) {
  console.error(`Set ${cfg.amountEnv} to a positive USD amount (e.g. export OFFICE24_OPENING_M1_USD=1000000)`);
  process.exit(1);
}

const MATERIAL_THRESHOLD = 10_000_000;
if (amount >= MATERIAL_THRESHOLD) {
  console.error(
    `Amount ${amount} exceeds single-leg seed limit ($${MATERIAL_THRESHOLD}). ` +
      'Material openings use the two-leg HO matrix: scripts/omnl/office24-hospitallers-1b-canary.sh and office24-hospitallers-1b-execute.sh',
  );
  process.exit(1);
}

const auth = Buffer.from(`${user}:${pass}`).toString('base64');
const headers = {
  Authorization: `Basic ${auth}`,
  'Fineract-Platform-TenantId': tenant,
  'Content-Type': 'application/json',
  Accept: 'application/json',
};

async function glIdForCode(glCode) {
  const res = await fetch(`${base}/glaccounts?limit=500`, { headers });
  if (!res.ok) throw new Error(`GL list failed (${res.status})`);
  const data = await res.json();
  const list = Array.isArray(data) ? data : [];
  const match = list.find((row) => String(row.glCode) === glCode);
  if (!match?.id) throw new Error(`GL code ${glCode} not found in Fineract tenant ${tenant}`);
  return Number(match.id);
}

const debitGlAccountId = await glIdForCode(cfg.debitGlCode);
const creditGlAccountId = await glIdForCode(cfg.creditGlCode);

const entry = {
  officeId: cfg.officeId,
  transactionDate: new Date().toISOString().slice(0, 10),
  referenceNumber: cfg.referenceNumber,
  comments: cfg.comments,
  debits: [{ glAccountId: debitGlAccountId, amount }],
  credits: [{ glAccountId: creditGlAccountId, amount }],
};

console.log(JSON.stringify({ dryRun, officeId: cfg.officeId, amount, debitGlAccountId, creditGlAccountId, entry }, null, 2));

if (dryRun) {
  console.log('Dry run — no journal posted.');
  process.exit(0);
}

const res = await fetch(`${base}/journalentries`, {
  method: 'POST',
  headers,
  body: JSON.stringify(entry),
});

const body = await res.text();
if (!res.ok) {
  console.error(`Fineract POST failed (${res.status}): ${body}`);
  process.exit(1);
}

console.log('Office 24 opening journal posted:', body);
