const userService = require("../services/userService");
const logger = require("../utils/logger");

// Controller methods for user operations
const getAllUsers = async (req, res) => {
  const queryParams = req.query; // Assuming you want to get parameters from the request body

  try {
    const users = await userService.getAllUsers(queryParams);
    res.json(users);
  } catch (error) {
    console.log(error);
    logger.error(`Error getting all users: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};


const getUserById = async (req, res) => {
  const { id } = req.params;
  const queryParams = req.body; // Assuming you want to get parameters from the request body
  try {
    const user = await userService.getUserById(id, queryParams);
    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }
    res.json(user);
  } catch (error) {
    logger.error(`Error getting user by ID: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};


const createUser = async (req, res) => {
  const { body } = req;
  try {
    const newUser = await userService.createUser(body);
    res.status(201).json(newUser);
  } catch (error) {
    logger.error(`Error creating user: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

const updateUser = async (req, res) => {
  const { id } = req.params;
  const { body } = req;
  try {
    const updatedUser = await userService.updateUser(id, body);
    if (!updatedUser) {
      return res.status(404).json({ error: "User not found" });
    }
    res.json(updatedUser);
  } catch (error) {     
    logger.error(`Error updating user: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

const deleteUser = async (req, res) => {
  const { id } = req.params;
  try {
    const deletedUser = await userService.deleteUser(id);
    if (!deletedUser) {
      return res.status(404).json({ error: "User not found" });
    }
    res.json({ message: "User deleted successfully" });
  } catch (error) {
    logger.error(`Error deleting user: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};


const checkLogin = async (req, res) => {
  const queryParams = req.body; // Assuming you want to get parameters from the request body

  try {
    const users = await userService.checkLogin(queryParams);
    res.json(users);
  } catch (error) {
    logger.error(`Error checking user credentials: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

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