/**
 * Initialize Chart of Accounts
 * 
 * This script initializes the standard Chart of Accounts
 * Run this after the migration has been applied.
 * 
 * Usage:
 *   ts-node scripts/initialize-chart-of-accounts.ts
 *   or
 *   npm run build && node dist/scripts/initialize-chart-of-accounts.js
 */

// Use relative import to avoid path alias issues
import { chartOfAccountsService, AccountCategory } from '../src/core/accounting/chart-of-accounts.service';

// Register tsconfig paths if needed
import { register } from 'tsconfig-paths';
import * as path from 'path';

const tsConfig = require('../tsconfig.json');
const baseUrl = path.resolve(__dirname, '..', tsConfig.compilerOptions.baseUrl || '.');
register({
  baseUrl,
  paths: tsConfig.compilerOptions.paths || {},
});

async function initializeChartOfAccounts() {
  try {
    console.log('Initializing Chart of Accounts...');
    
    await chartOfAccountsService.initializeChartOfAccounts();
    
    console.log('✅ Chart of Accounts initialized successfully!');
    
    // Verify by getting account count
    const accounts = await chartOfAccountsService.getChartOfAccounts();
    console.log(`✅ Total accounts created: ${accounts.length}`);
    
    // Show summary by category
    const assets = await chartOfAccountsService.getAccountsByCategory(
      AccountCategory.ASSET
    );
    const liabilities = await chartOfAccountsService.getAccountsByCategory(
      AccountCategory.LIABILITY
    );
    const equity = await chartOfAccountsService.getAccountsByCategory(
      AccountCategory.EQUITY
    );
    const revenue = await chartOfAccountsService.getAccountsByCategory(
      AccountCategory.REVENUE
    );
    const expenses = await chartOfAccountsService.getAccountsByCategory(
      AccountCategory.EXPENSE
    );
    
    console.log('\n📊 Account Summary:');
    console.log(`   Assets: ${assets.length}`);
    console.log(`   Liabilities: ${liabilities.length}`);
    console.log(`   Equity: ${equity.length}`);
    console.log(`   Revenue: ${revenue.length}`);
    console.log(`   Expenses: ${expenses.length}`);
    
    process.exit(0);
  } catch (error: any) {
    console.error('❌ Error initializing Chart of Accounts:', error.message);
    console.error(error.stack);
    process.exit(1);
  }
}

// Run if called directly
if (require.main === module) {
  initializeChartOfAccounts();
}

export { initializeChartOfAccounts };
