const bcrypt = require('bcrypt');
// Use SQLite instead of PostgreSQL
const db = require('../config/sqlite-db');
const { roles } = require('../middleware/auth.middleware');

// Get all users
const getAllUsers = async (req, res) => {
  try {
    // Only super_admin can get all users
    const users = await db.query('SELECT id, username, email, role, created_at FROM users');
    res.status(200).json(users.rows);
  } catch (error) {
    console.error('Error getting users:', error);
    res.status(500).json({ message: 'Server error while retrieving users' });
  }
};

// Get user by ID
const getUserById = async (req, res) => {
  try {
    const userId = req.params.id;
    const requestingUserId = req.user.id;
    const requestingUserRole = req.user.role;

    // Check if user is super_admin or requesting their own info
    if (requestingUserRole !== roles.SUPER_ADMIN && requestingUserId !== userId) {
      return res.status(403).json({ message: 'Not authorized to access this user information' });
    }

    const user = await db.query(
      'SELECT id, username, email, role, created_at FROM users WHERE id = $1', 
      [userId]
    );

    if (user.rows.length === 0) {
      return res.status(404).json({ message: 'User not found' });
    }

    res.status(200).json(user.rows[0]);
  } catch (error) {
    console.error('Error getting user by ID:', error);
    res.status(500).json({ message: 'Server error while retrieving user' });
  }
};

// Create new user (super_admin only)
const createUser = async (req, res) => {
  try {
    const { username, email, password, role } = req.body;

    // Check if user already exists
    const userExists = await db.query('SELECT * FROM users WHERE email = $1', [email]);
    if (userExists.rows.length > 0) {
      return res.status(400).json({ message: 'User already exists' });
    }

    // Hash password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // Validate role
    const validRole = role && (role === roles.SUPER_ADMIN || role === roles.ADMIN || role === roles.GUEST)
      ? role
      : roles.GUEST;

    // Create user
    const newUser = await db.query(
      'INSERT INTO users (username, email, password, role) VALUES ($1, $2, $3, $4) RETURNING id, username, email, role, created_at',
      [username, email, hashedPassword, validRole]
    );

    res.status(201).json(newUser.rows[0]);
  } catch (error) {
    console.error('Error creating user:', error);
    res.status(500).json({ message: 'Server error while creating user' });
  }
};

// Update user
const updateUser = async (req, res) => {
  try {
    const userId = req.params.id;
    const requestingUserId = req.user.id;
    const requestingUserRole = req.user.role;
    const { username, email, password, role } = req.body;

    // Check if user is super_admin or updating their own info
    if (requestingUserRole !== roles.SUPER_ADMIN && requestingUserId != userId) {
      return res.status(403).json({ message: 'Not authorized to update this user' });
    }
    
    console.log(`User update request: requestingUserId=${requestingUserId}, requestingUserRole=${requestingUserRole}, targetUserId=${userId}`);
    if (password) {
      console.log('Password update requested');
    }

    // Get existing user data
    const existingUser = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
    if (existingUser.rows.length === 0) {
      return res.status(404).json({ message: 'User not found' });
    }

    // Only super_admin can change roles
    let updatedRole = existingUser.rows[0].role;
    if (requestingUserRole === roles.SUPER_ADMIN && role) {
      // Validate role
      updatedRole = (role === roles.SUPER_ADMIN || role === roles.ADMIN || role === roles.GUEST)
        ? role
        : existingUser.rows[0].role;
    }

    // Hash password if provided
    let updatedPassword = existingUser.rows[0].password;
    if (password) {
      const salt = await bcrypt.genSalt(10);
      updatedPassword = await bcrypt.hash(password, salt);
    }

    // Update user
    const updatedUser = await db.query(
      `UPDATE users 
       SET username = $1, 
           email = $2, 
           password = $3, 
           role = $4
       WHERE id = $5
       RETURNING id, username, email, role, created_at`,
      [
        username || existingUser.rows[0].username,
        email || existingUser.rows[0].email,
        updatedPassword,
        updatedRole,
        userId
      ]
    );

    res.status(200).json(updatedUser.rows[0]);
  } catch (error) {
    console.error('Error updating user:', error);
    res.status(500).json({ message: 'Server error while updating user' });
  }
};

// Delete user
const deleteUser = async (req, res) => {
  try {
    const userId = req.params.id;
    const requestingUserId = req.user.id;

    // Prevent super_admin from deleting themselves
    if (requestingUserId === userId) {
      return res.status(400).json({ message: 'Cannot delete your own account' });
    }

    // Check if user exists
    const existingUser = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
    if (existingUser.rows.length === 0) {
      return res.status(404).json({ message: 'User not found' });
    }

    // Delete user
    await db.query('DELETE FROM users WHERE id = $1', [userId]);
    
    res.status(200).json({ message: 'User deleted successfully' });
  } catch (error) {
    console.error('Error deleting user:', error);
    res.status(500).json({ message: 'Server error while deleting user' });
  }
};

module.exports = {
  getAllUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser
};
