/**
 * Initialize Chart of Accounts - Simplified Version
 * Direct database access without service layer
 */

import { PrismaClient } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';

const prisma = new PrismaClient();

const accounts = [
  // Assets
  { code: '1000', name: 'ASSETS', category: 'ASSET', level: 1, balance: 'DEBIT', type: 'Asset', usgaap: 'Assets', ifrs: 'Assets', desc: 'Total Assets', system: true },
  { code: '1100', name: 'Current Assets', category: 'ASSET', parent: '1000', level: 2, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Current Assets', ifrs: 'Current Assets', desc: 'Assets expected to be converted to cash within one year', system: true },
  { code: '1110', name: 'Cash and Cash Equivalents', category: 'ASSET', parent: '1100', level: 3, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Cash and Cash Equivalents', ifrs: 'Cash and Cash Equivalents', desc: 'Cash on hand and in banks, short-term investments', system: true },
  { code: '1111', name: 'Cash on Hand', category: 'ASSET', parent: '1110', level: 4, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Cash', ifrs: 'Cash', desc: 'Physical currency and coins', system: false },
  { code: '1112', name: 'Cash in Banks', category: 'ASSET', parent: '1110', level: 4, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Cash', ifrs: 'Cash', desc: 'Deposits in commercial banks', system: false },
  { code: '1120', name: 'Accounts Receivable', category: 'ASSET', parent: '1100', level: 3, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Trade Receivables', ifrs: 'Trade Receivables', desc: 'Amounts owed by customers and counterparties', system: true },
  { code: '1130', name: 'Settlement Assets', category: 'ASSET', parent: '1100', level: 3, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Other Current Assets', ifrs: 'Other Current Assets', desc: 'Assets held for settlement purposes', system: true },
  { code: '1140', name: 'CBDC Holdings', category: 'ASSET', parent: '1100', level: 3, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Digital Assets', ifrs: 'Cryptocurrency Assets', desc: 'Central Bank Digital Currency holdings', system: true },
  { code: '1150', name: 'GRU Holdings', category: 'ASSET', parent: '1100', level: 3, balance: 'DEBIT', type: 'Current Asset', usgaap: 'Digital Assets', ifrs: 'Financial Assets', desc: 'Global Reserve Unit holdings', system: true },
  { code: '1200', name: 'Non-Current Assets', category: 'ASSET', parent: '1000', level: 2, balance: 'DEBIT', type: 'Non-Current Asset', usgaap: 'Non-Current Assets', ifrs: 'Non-Current Assets', desc: 'Long-term assets', system: true },
  { code: '1210', name: 'Property, Plant and Equipment', category: 'ASSET', parent: '1200', level: 3, balance: 'DEBIT', type: 'Non-Current Asset', usgaap: 'Property, Plant and Equipment', ifrs: 'Property, Plant and Equipment', desc: 'Tangible fixed assets', system: true },
  
  // Liabilities
  { code: '2000', name: 'LIABILITIES', category: 'LIABILITY', level: 1, balance: 'CREDIT', type: 'Liability', usgaap: 'Liabilities', ifrs: 'Liabilities', desc: 'Total Liabilities', system: true },
  { code: '2100', name: 'Current Liabilities', category: 'LIABILITY', parent: '2000', level: 2, balance: 'CREDIT', type: 'Current Liability', usgaap: 'Current Liabilities', ifrs: 'Current Liabilities', desc: 'Obligations due within one year', system: true },
  { code: '2110', name: 'Accounts Payable', category: 'LIABILITY', parent: '2100', level: 3, balance: 'CREDIT', type: 'Current Liability', usgaap: 'Accounts Payable', ifrs: 'Trade Payables', desc: 'Amounts owed to suppliers and counterparties', system: true },
  { code: '2140', name: 'CBDC Liabilities', category: 'LIABILITY', parent: '2100', level: 3, balance: 'CREDIT', type: 'Current Liability', usgaap: 'Digital Currency Liabilities', ifrs: 'Financial Liabilities', desc: 'CBDC issued and outstanding', system: true },
  { code: '2150', name: 'GRU Liabilities', category: 'LIABILITY', parent: '2100', level: 3, balance: 'CREDIT', type: 'Current Liability', usgaap: 'Digital Currency Liabilities', ifrs: 'Financial Liabilities', desc: 'GRU issued and outstanding', system: true },
  
  // Equity
  { code: '3000', name: 'EQUITY', category: 'EQUITY', level: 1, balance: 'CREDIT', type: 'Equity', usgaap: 'Equity', ifrs: 'Equity', desc: 'Total Equity', system: true },
  { code: '3100', name: 'Capital', category: 'EQUITY', parent: '3000', level: 2, balance: 'CREDIT', type: 'Equity', usgaap: 'Stockholders Equity', ifrs: 'Share Capital', desc: 'Paid-in capital', system: true },
  { code: '3200', name: 'Retained Earnings', category: 'EQUITY', parent: '3000', level: 2, balance: 'CREDIT', type: 'Equity', usgaap: 'Retained Earnings', ifrs: 'Retained Earnings', desc: 'Accumulated net income', system: true },
  
  // Revenue
  { code: '4000', name: 'REVENUE', category: 'REVENUE', level: 1, balance: 'CREDIT', type: 'Revenue', usgaap: 'Revenue', ifrs: 'Revenue', desc: 'Total Revenue', system: true },
  { code: '4100', name: 'Operating Revenue', category: 'REVENUE', parent: '4000', level: 2, balance: 'CREDIT', type: 'Revenue', usgaap: 'Operating Revenue', ifrs: 'Revenue from Contracts with Customers', desc: 'Revenue from primary operations', system: true },
  { code: '4110', name: 'Interest Income', category: 'REVENUE', parent: '4100', level: 3, balance: 'CREDIT', type: 'Revenue', usgaap: 'Interest Income', ifrs: 'Interest Income', desc: 'Interest earned on loans and investments', system: true },
  
  // Expenses
  { code: '5000', name: 'EXPENSES', category: 'EXPENSE', level: 1, balance: 'DEBIT', type: 'Expense', usgaap: 'Expenses', ifrs: 'Expenses', desc: 'Total Expenses', system: true },
  { code: '5100', name: 'Operating Expenses', category: 'EXPENSE', parent: '5000', level: 2, balance: 'DEBIT', type: 'Expense', usgaap: 'Operating Expenses', ifrs: 'Operating Expenses', desc: 'Expenses from primary operations', system: true },
  { code: '5110', name: 'Interest Expense', category: 'EXPENSE', parent: '5100', level: 3, balance: 'DEBIT', type: 'Expense', usgaap: 'Interest Expense', ifrs: 'Finance Costs', desc: 'Interest paid on borrowings', system: true },
];

async function initialize() {
  try {
    console.log('Initializing Chart of Accounts...');
    
    let count = 0;
    for (const acc of accounts) {
      await prisma.chartOfAccount.upsert({
        where: { accountCode: acc.code },
        update: {
          accountName: acc.name,
          category: acc.category,
          parentAccountCode: acc.parent || null,
          level: acc.level,
          normalBalance: acc.balance,
          accountType: acc.type,
          usgaapClassification: acc.usgaap,
          ifrsClassification: acc.ifrs,
          description: acc.desc,
          isActive: true,
        },
        create: {
          id: uuidv4(),
          accountCode: acc.code,
          accountName: acc.name,
          category: acc.category,
          parentAccountCode: acc.parent || null,
          level: acc.level,
          normalBalance: acc.balance,
          accountType: acc.type,
          usgaapClassification: acc.usgaap,
          ifrsClassification: acc.ifrs,
          description: acc.desc,
          isActive: true,
          isSystemAccount: acc.system,
          metadata: {},
        },
      });
      count++;
    }
    
    console.log(`✅ Chart of Accounts initialized successfully!`);
    console.log(`✅ Total accounts created: ${count}`);
    
    // Show summary
    const summary = await prisma.chartOfAccount.groupBy({
      by: ['category'],
      where: { isActive: true },
      _count: { id: true },
    });
    
    console.log('\n📊 Account Summary:');
    for (const s of summary) {
      console.log(`   ${s.category}: ${s._count.id}`);
    }
    
    process.exit(0);
  } catch (error: any) {
    console.error('❌ Error initializing Chart of Accounts:', error.message);
    console.error(error.stack);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

if (require.main === module) {
  initialize();
}

export { initialize };
