const db = require('../database/database'); // Adjust path if needed
const UnitOfWork = require('../database/UnitOfWork');
const argon2 = require('argon2');

async function createAdminUser() {
  return;
  // const adminEmail = process.env.ADMIN_EMAIL || 'office@profit-planet.com';
  const adminEmail = process.env.ADMIN_EMAIL || 'alexander.ibrahim.ai@gmail.com';
  // const adminEmail = process.env.ADMIN_EMAIL || 'loki.aahi@gmail.com';
  const adminPassword = process.env.ADMIN_PASSWORD || 'Chalanger75$%';
  // const adminPassword = process.env.ADMIN_PASSWORD || 'W.profit-planet.com.2025';
  const firstName = process.env.ADMIN_FIRST_NAME || 'Admin';
  const lastName = process.env.ADMIN_LAST_NAME || 'User';


  const uow = new UnitOfWork(); // No need to pass pool
  await uow.start();
  try {
    // Check if admin user exists
    const [users] = await uow.connection.query(
      `SELECT id FROM users WHERE email = ? AND role = 'admin' LIMIT 1`, [adminEmail]
    );
    let userId;
    const hashedPassword = await argon2.hash(adminPassword);
    if (users.length) {
      userId = users[0].id;
      // Update password hash to match new secret
      await uow.connection.query(
        `UPDATE users SET password = ? WHERE id = ?`,
        [hashedPassword, userId]
      );
      console.log('✅ Admin user password updated');
    } else {
      // Create admin user
      const [userResult] = await uow.connection.query(
        `INSERT INTO users (email, password, user_type, role, created_at) VALUES (?, ?, 'personal', 'admin', NOW())`,
        [adminEmail, hashedPassword]
      );
      userId = userResult.insertId;

      // Insert into personal_profiles
      await uow.connection.query(
        `INSERT INTO personal_profiles (user_id, first_name, last_name) VALUES (?, ?, ?)`,
        [userId, firstName, lastName]
      );

      // Insert into user_status (active, admin verified)
      await uow.connection.query(
        `INSERT INTO user_status (user_id, status, is_admin_verified, admin_verified_at, email_verified, profile_completed, documents_uploaded, contract_signed)
         VALUES (?, 'active', 1, NOW(), 1, 1, 1, 1)`,
        [userId]
      );

      // Insert into user_settings
      await uow.connection.query(
        `INSERT INTO user_settings (user_id) VALUES (?)`,
        [userId]
      );

      // Assign can_create_referrals permission (fix name)
      const [permRows] = await uow.connection.query(
        `SELECT id FROM permissions WHERE name = 'can_create_referrals' LIMIT 1`
      );
      if (permRows.length) {
        await uow.connection.query(
          `INSERT INTO user_permissions (user_id, permission_id) VALUES (?, ?)`,
          [userId, permRows[0].id]
        );
      }
      console.log('✅ Admin user created and initialized');
    }
    await uow.commit();
  } catch (error) {
    await uow.rollback(error);
    console.error('💥 Failed to create admin user:', error);
    throw error;
  }
}

module.exports = createAdminUser;