#!/usr/bin/env node

/**
 * WakaTraffic Demo Account Seeding Script
 * Creates demo admin and user accounts for testing
 */

const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');
require('dotenv').config();

// Demo credentials
const DEMO_ACCOUNTS = {
  admin: {
    email: 'admin@wakatraffic.demo',
    password: 'AdminDemo123!',
    firstName: 'Admin',
    lastName: 'User',
    mobile: '1234567890',
    role: 'admin',
    balance: 1000.00
  },
  user: {
    email: 'user@wakatraffic.demo',
    password: 'UserDemo123!',
    firstName: 'Demo',
    lastName: 'User',
    mobile: '0987654321',
    role: 'user',
    balance: 100.00
  },
  user2: {
    email: 'customer@wakatraffic.demo',
    password: 'CustomerDemo123!',
    firstName: 'Customer',
    lastName: 'Account',
    mobile: '5555555555',
    role: 'user',
    balance: 50.00
  }
};

async function seedDemoAccounts() {
  let connection;

  try {
    console.log('\n╔════════════════════════════════════════════════════════════╗');
    console.log('║     WakaTraffic Demo Account Seeding Script                ║');
    console.log('╚════════════════════════════════════════════════════════════╝\n');

    // Resolve correct DB host for WSL2
    function getDbHost() {
      const h = process.env.DB_HOST || 'localhost';
      if (h !== 'localhost' && h !== '127.0.0.1') return h;
      try {
        const fs = require('fs');
        const resolv = fs.readFileSync('/etc/resolv.conf', 'utf8');
        if (resolv.includes('WSL')) {
          const m = resolv.match(/nameserver\s+([\d.]+)/);
          if (m) { console.log('WSL2 detected, using host:', m[1]); return m[1]; }
        }
      } catch(e) {}
      return h;
    }

    // Create connection pool
    connection = await mysql.createConnection({
      host: getDbHost(),
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || '',
      database: process.env.DB_NAME || 'wakatraffic'
    });

    console.log('✅ Connected to database\n');

    // Seed each account
    for (const [key, account] of Object.entries(DEMO_ACCOUNTS)) {
      await seedAccount(connection, account, key);
    }

    console.log('\n╔════════════════════════════════════════════════════════════╗');
    console.log('║     ✅ DEMO ACCOUNTS CREATED SUCCESSFULLY!                 ║');
    console.log('╚════════════════════════════════════════════════════════════╝\n');

    displayLoginCredentials();

  } catch (error) {
    console.error('❌ Error seeding accounts:', error.message);
    process.exit(1);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

async function seedAccount(connection, account, key) {
  try {
    // Hash password
    const passwordHash = await bcrypt.hash(account.password, 10);

    // Generate username from email
    const username = account.email.split('@')[0];

    // Check if account exists
    const [existingUsers] = await connection.execute(
      'SELECT id FROM users WHERE email = ?',
      [account.email]
    );

    if (existingUsers.length > 0) {
      console.log(`⊘ ${key.toUpperCase()}: Account already exists (${account.email})`);
      return;
    }

    // Insert user
    const [result] = await connection.execute(
      `INSERT INTO users (username, email, password_hash, first_name, last_name, mobile_number, balance, role, status, email_verified, created_at, updated_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', 1, NOW(), NOW())`,
      [
        username,
        account.email,
        passwordHash,
        account.firstName,
        account.lastName,
        account.mobile,
        account.balance,
        account.role
      ]
    );

    console.log(`✅ ${key.toUpperCase()}: Created successfully`);
    console.log(`   Email: ${account.email}`);
    console.log(`   Password: ${account.password}`);
    console.log(`   Balance: $${account.balance.toFixed(2)}`);
    console.log(`   Role: ${account.role}`);
    console.log();

  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      console.log(`⊘ ${key.toUpperCase()}: Account already exists`);
    } else {
      console.error(`❌ ${key.toUpperCase()}: Error - ${error.message}`);
    }
  }
}

function displayLoginCredentials() {
  console.log('═══════════════════════════════════════════════════════════\n');
  console.log('📋 DEMO LOGIN CREDENTIALS\n');
  console.log('═══════════════════════════════════════════════════════════\n');

  console.log('👨‍💼 ADMIN ACCOUNT');
  console.log('─────────────────────────────────────────────────────────');
  console.log(`Email:    ${DEMO_ACCOUNTS.admin.email}`);
  console.log(`Password: ${DEMO_ACCOUNTS.admin.password}`);
  console.log(`Balance:  $${DEMO_ACCOUNTS.admin.balance.toFixed(2)}`);
  console.log(`Role:     Administrator (full access)\n`);

  console.log('👤 USER ACCOUNTS (for testing)');
  console.log('─────────────────────────────────────────────────────────\n');

  console.log('User 1:');
  console.log(`Email:    ${DEMO_ACCOUNTS.user.email}`);
  console.log(`Password: ${DEMO_ACCOUNTS.user.password}`);
  console.log(`Balance:  $${DEMO_ACCOUNTS.user.balance.toFixed(2)}`);
  console.log(`Role:     Regular User\n`);

  console.log('User 2:');
  console.log(`Email:    ${DEMO_ACCOUNTS.user2.email}`);
  console.log(`Password: ${DEMO_ACCOUNTS.user2.password}`);
  console.log(`Balance:  $${DEMO_ACCOUNTS.user2.balance.toFixed(2)}`);
  console.log(`Role:     Regular User\n`);

  console.log('═══════════════════════════════════════════════════════════\n');
  console.log('🔐 SECURITY NOTES:');
  console.log('─────────────────────────────────────────────────────────');
  console.log('• These are DEMO accounts for testing only');
  console.log('• Do NOT use in production');
  console.log('• Change passwords before sharing server');
  console.log('• Delete demo accounts before deploying to production\n');

  console.log('📝 HOW TO USE:');
  console.log('─────────────────────────────────────────────────────────');
  console.log('1. Start the server: npm start');
  console.log('2. Open frontend application');
  console.log('3. Click "Login"');
  console.log('4. Use credentials above');
  console.log('5. Test features (create orders, check balance, etc.)\n');

  console.log('🔄 API LOGIN ENDPOINT:');
  console.log('─────────────────────────────────────────────────────────');
  console.log('POST /api/auth/login');
  console.log(`Example: curl -X POST http://localhost:5000/api/auth/login \\`);
  console.log(`  -H "Content-Type: application/json" \\`);
  console.log(`  -d '{"email":"admin@wakatraffic.demo","password":"AdminDemo123!"}'`);
  console.log(`\nResponse will include JWT token for authenticated requests\n`);

  console.log('═══════════════════════════════════════════════════════════\n');
}

// Run seeding
seedDemoAccounts().catch(error => {
  console.error('Fatal error:', error);
  process.exit(1);
});
