const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const User = require('../models/User');
const dotenv = require('dotenv');

// Load environment variables
dotenv.config();

// Connect to MongoDB
const connectDB = async () => {
  try {
    console.log('MongoDB URI:', process.env.MONGO_URI);
    await mongoose.connect(process.env.MONGO_URI);
    console.log('MongoDB Connected');
    return true;
  } catch (error) {
    console.error('MongoDB Connection Error:', error);
    return false;
  }
};

// Function to create admin
const createAdmin = async () => {
  try {
    // Check if admin exists with valid email format
    let admin = await User.findOne({ email: 'admin@example.com' });
    
    if (admin) {
      console.log('Admin user already exists:');
      console.log({
        id: admin._id,
        name: admin.name,
        email: admin.email,
        isAdmin: admin.isAdmin
      });
      
      // Update admin to ensure correct properties
      admin.name = 'Администратор';
      admin.isAdmin = true;
      admin.isActive = true;
      await admin.save();
      
      console.log('Admin user updated');
      return admin;
    }
    
    // Create new admin user if doesn't exist
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash('admin124', salt);
    
    admin = new User({
      name: 'Администратор',
      email: 'admin@example.com', // Use valid email format
      password: hashedPassword,
      dateOfBirth: new Date('1990-01-01'),
      gender: 'other',
      isActive: true,
      isAdmin: true,
      location: {
        city: 'Admin',
        country: 'System'
      }
    });
    
    await admin.save();
    console.log('Admin user created successfully:');
    console.log({
      id: admin._id,
      name: admin.name,
      email: admin.email,
      isAdmin: admin.isAdmin
    });
    
    return admin;
  } catch (error) {
    console.error('Error creating admin:', error);
    return null;
  }
};

// Create admin alias with email = admin@example.com
const createAdminAlias = async () => {
  try {
    // Check if admin@example.com exists
    let adminAlias = await User.findOne({ email: 'admin@example.com' });
    
    if (adminAlias) {
      console.log('Admin alias already exists');
      return adminAlias;
    }
    
    // Find the main admin user
    const mainAdmin = await User.findOne({ email: 'admin' });
    if (!mainAdmin) {
      console.error('Cannot create admin alias: main admin account not found');
      return null;
    }
    
    // Create admin alias
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash('admin124', salt);
    
    adminAlias = new User({
      name: 'Администратор',
      email: 'admin@example.com',
      password: hashedPassword,
      dateOfBirth: new Date('1990-01-01'),
      gender: 'other',
      isActive: true,
      isAdmin: true,
      location: {
        city: 'Admin',
        country: 'System'
      }
    });
    
    await adminAlias.save();
    console.log('Admin alias created successfully:');
    console.log({
      id: adminAlias._id,
      name: adminAlias.name,
      email: adminAlias.email,
      isAdmin: adminAlias.isAdmin
    });
    
    return adminAlias;
  } catch (error) {
    console.error('Error creating admin alias:', error);
    return null;
  }
};

// Main function
const main = async () => {
  console.log('Testing Admin Creation...');
  
  // Connect to database
  const connected = await connectDB();
  if (!connected) {
    console.error('Failed to connect to database');
    process.exit(1);
  }
  
  // Create admin user
  const admin = await createAdmin();
  if (!admin) {
    console.error('Failed to create admin user');
    process.exit(1);
  }
  
  // Create admin alias
  const adminAlias = await createAdminAlias();
    console.log('\nAdmin Credentials:');
  console.log('Email: admin@example.com');
  console.log('Password: admin124');
  console.log('\nYou can also use "admin" as username and "admin124" as password');
  
  console.log('\nDone!');
  process.exit(0);
};

main();
