/**
 * One-time chart of accounts seed script.
 * Merges seeds/chart_of_accounts.seed.json with the live db/chart_of_accounts.json
 * preserving all existing entries and only adding missing seed entries.
 *
 * Usage: node scripts/seed-chart-of-accounts.mjs
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(__dirname, '..');

const DB_FILE     = path.join(root, 'db', 'chart_of_accounts.json');
const SEED_FILE   = path.join(root, 'seeds', 'chart_of_accounts.seed.json');

function readJson(filePath, fallback = []) {
  try {
    if (!fs.existsSync(filePath)) return fallback;
    const raw = fs.readFileSync(filePath, 'utf-8').trim();
    return raw ? JSON.parse(raw) : fallback;
  } catch {
    return fallback;
  }
}

const current = readJson(DB_FILE);
const seed    = readJson(SEED_FILE);

if (!seed.length) {
  console.error('ERROR: Seed file is empty or missing:', SEED_FILE);
  process.exit(1);
}

const byId   = new Map(current.map((e, i) => [String(e?.id   ?? ''), i]));
const byCode = new Map(current.map((e, i) => [String(e?.code ?? ''), i]));
const merged = current.map(e => ({ ...e }));
let added = 0, skipped = 0;

for (const entry of seed) {
  const id   = String(entry?.id   ?? '').trim();
  const code = String(entry?.code ?? '').trim();
  const existsAt = byId.get(id) ?? byCode.get(code);

  if (existsAt !== undefined) {
    skipped++;
    continue;
  }

  merged.push({ ...entry });
  const idx = merged.length - 1;
  byId.set(id, idx);
  byCode.set(code, idx);
  added++;
}

// Ensure db/ directory exists
const dbDir = path.join(root, 'db');
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });

fs.writeFileSync(DB_FILE, JSON.stringify(merged, null, 2), 'utf-8');

console.log(`Done. Total accounts: ${merged.length} | Added: ${added} | Already existed: ${skipped}`);
