import bcrypt from 'bcryptjs';
import dotenv from 'dotenv';
import { initializeDatabase, dbRun, dbGet } from '../config/database.js';

// Load environment variables
dotenv.config();

async function initDB() {
  try {
    console.log('Initializing database...');
    
    // Create tables
    await initializeDatabase();

    // Check if admin user exists
    const adminExists = await dbGet(
      'SELECT * FROM users WHERE username = ?',
      ['admin']
    );

    if (!adminExists) {
      // Create admin user with hashed password
      const hashedPassword = await bcrypt.hash('admin123', 10);
      
      await dbRun(
        `INSERT INTO users (username, password, email, role) 
         VALUES (?, ?, ?, ?)`,
        ['admin', hashedPassword, 'admin@zarnaira.com', 'admin']
      );

      if (process.env.NODE_ENV === 'production') {
        console.log('✓ Admin user created successfully');
        console.log('⚠️  Please change default admin password immediately after first login');
      } else {
        console.log('✓ Admin user created successfully');
        console.log('  Username: admin');
        console.log('  Password: admin123');
        console.log('  Email: admin@zarnaira.com');
      }
    } else {
      console.log('✓ Admin user already exists');
    }

    // Insert default exchange rates if not exists
    const ratesExist = await dbGet('SELECT * FROM exchange_rates LIMIT 1');
    
    if (!ratesExist) {
      await dbRun(
        `INSERT INTO exchange_rates (currency_pair, buy_rate, sell_rate) 
         VALUES (?, ?, ?)`,
        ['ZAR-NGN', 22.50, 23.00]
      );
      
      await dbRun(
        `INSERT INTO exchange_rates (currency_pair, buy_rate, sell_rate) 
         VALUES (?, ?, ?)`,
        ['NGN-ZAR', 0.043, 0.044]
      );

      console.log('✓ Default exchange rates created');
    } else {
      console.log('✓ Exchange rates already exist');
    }

    console.log('\n✓ Database initialization complete!');
    process.exit(0);
  } catch (error) {
    console.error('✗ Error initializing database:', error);
    process.exit(1);
  }
}

initDB();
