import bcrypt from 'bcryptjs';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const USERS_FILE = path.join(__dirname, 'users.json');

// Default admin user - change this password!
const DEFAULT_ADMIN = {
  username: 'admin',
  password: 'seedsrhasbestfeet', // This will be hashed
  role: 'admin'
};

// Initialize users file if it doesn't exist
async function initializeUsers() {
  try {
    if (!(await fs.pathExists(USERS_FILE))) {
      const hashedPassword = await bcrypt.hash(DEFAULT_ADMIN.password, 10);
      const users = {
        admin: {
          username: DEFAULT_ADMIN.username,
          passwordHash: hashedPassword,
          role: DEFAULT_ADMIN.role,
          createdAt: new Date().toISOString()
        }
      };
      await fs.writeJSON(USERS_FILE, users, { spaces: 2 });
      console.log('🔐 Created default admin user (username: admin, password: admin123)');
      console.log('⚠️  IMPORTANT: Change the default password immediately!');
    }
  } catch (error) {
    console.error('Error initializing users:', error);
  }
}

// Load users from file
async function loadUsers() {
  try {
    if (await fs.pathExists(USERS_FILE)) {
      return await fs.readJSON(USERS_FILE);
    }
    return {};
  } catch (error) {
    console.error('Error loading users:', error);
    return {};
  }
}

// Save users to file
async function saveUsers(users) {
  try {
    await fs.writeJSON(USERS_FILE, users, { spaces: 2 });
  } catch (error) {
    console.error('Error saving users:', error);
    throw error;
  }
}

// Authenticate user
export async function authenticateUser(username, password) {
  try {
    const users = await loadUsers();
    const user = users[username];
    
    if (!user) {
      return null;
    }
    
    const isValidPassword = await bcrypt.compare(password, user.passwordHash);
    if (!isValidPassword) {
      return null;
    }
    
    // Return user without password hash
    return {
      username: user.username,
      role: user.role,
      createdAt: user.createdAt
    };
  } catch (error) {
    console.error('Error authenticating user:', error);
    return null;
  }
}

// Get user by username (without password)
export async function getUserByUsername(username) {
  try {
    const users = await loadUsers();
    const user = users[username];
    
    if (!user) {
      return null;
    }
    
    return {
      username: user.username,
      role: user.role,
      createdAt: user.createdAt
    };
  } catch (error) {
    console.error('Error getting user:', error);
    return null;
  }
}

// Change user password
export async function changeUserPassword(username, oldPassword, newPassword) {
  try {
    const users = await loadUsers();
    const user = users[username];
    
    if (!user) {
      return { success: false, message: 'User not found' };
    }
    
    const isValidOldPassword = await bcrypt.compare(oldPassword, user.passwordHash);
    if (!isValidOldPassword) {
      return { success: false, message: 'Current password is incorrect' };
    }
    
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);
    users[username].passwordHash = hashedNewPassword;
    users[username].updatedAt = new Date().toISOString();
    
    await saveUsers(users);
    return { success: true, message: 'Password changed successfully' };
  } catch (error) {
    console.error('Error changing password:', error);
    return { success: false, message: 'Failed to change password' };
  }
}

// Initialize users on module load
await initializeUsers();