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

async function createTestUser() {
  try {
    // Create database connection
    const connection = await mysql.createConnection({
      host: '172.20.0.1',
      user: 'root',
      password: '',
      database: 'wakatraffic'
    });

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

    // Hash password
    const password = 'Test123456';
    const hashedPassword = await bcrypt.hash(password, 10);

    // Check if user exists
    const [existing] = await connection.execute(
      'SELECT id, email FROM users WHERE email = ?',
      ['testuser@wakatraffic.com']
    );

    if (existing.length > 0) {
      console.log('⚠️  User already exists. Updating...');

      // Update existing user - set as verified and regular user
      await connection.execute(
        `UPDATE users SET
          password_hash = ?,
          email_verified = 1,
          role = 'user',
          status = 'active',
          first_name = 'Test',
          last_name = 'User'
        WHERE email = ?`,
        [hashedPassword, 'testuser@wakatraffic.com']
      );

      console.log('✅ Existing user updated');
    } else {
      // Insert new user
      await connection.execute(
        `INSERT INTO users
        (username, email, password_hash, first_name, last_name, mobile_number, role, status, email_verified, balance, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
        [
          'testuser',
          'testuser@wakatraffic.com',
          hashedPassword,
          'Test',
          'User',
          '+2348012345678',
          'user',
          'active',
          1, // email_verified
          5000.00 // starting balance
        ]
      );

      console.log('✅ New user created');
    }

    // Get user details
    const [users] = await connection.execute(
      'SELECT id, email, first_name, last_name, role, status, balance, email_verified FROM users WHERE email = ?',
      ['testuser@wakatraffic.com']
    );

    console.log('\n📋 Test User Account Created:');
    console.log('================================');
    console.log('Email:', users[0].email);
    console.log('Password: Test123456');
    console.log('Name:', users[0].first_name, users[0].last_name);
    console.log('Role:', users[0].role);
    console.log('Status:', users[0].status);
    console.log('Balance: ₦' + parseFloat(users[0].balance).toLocaleString());
    console.log('Email Verified:', users[0].email_verified ? 'Yes' : 'No');
    console.log('\n🌐 Login at: http://localhost:5000');
    console.log('================================\n');

    await connection.end();

  } catch (error) {
    console.error('❌ Error:', error.message);
    process.exit(1);
  }
}

createTestUser();
