const TblFuncionario = require("../models/TblFuncionarios");
const customQueryHelper = require('../utils/databaseCustomQueryHelper');

const getAllUsers = async (queryParams = {}) => {
  const result = await customQueryHelper.executeDynamicQuery("view_Front_FuncionariosGlobalAcessos", queryParams);

  return result;
};

const getUserById = async (id, queryParams = {}) => {
  queryParams = { intId: id, ...queryParams };
  
  const result = await customQueryHelper.executeDynamicQuery("view_Front_FuncionariosGlobalAcessos", queryParams);

  return result;
};



const createUser = async (userData) => {
  return TblFuncionario.create(userData);
};

const updateUser = async (id, userData) => {
  const user = await TblFuncionario.findByPk(id);
  if (!user) {
    throw new Error("User not found");
  }
 
  console.log(userData);
  return user.update(userData);
};

const deleteUser = async (id) => {
  // Assuming TblFuncionario is your Sequelize model
  const result = await TblFuncionario.update(
    { bitEliminado: true },
    { where: { intId: id } }
  );

  // The 'result' object contains information about the operation
  const affectedRows = result[0];

  if (affectedRows === 0) {
    throw new Error("User not found");
  }

  // You might want to return additional information if needed
  return { success: true, message: "User soft deleted successfully" };
};

const checkLogin = async (queryParams) => {
  try {
    // Execute a view to check login credentials
    const result = await customQueryHelper.executeDynamicQuery("view_Front_FuncionariosCheckPermissions", queryParams);
    // Process the result and return appropriate response
    // Modify this part based on your login validation logic
   // Process the result and return appropriate response

   if (result && typeof result === 'object' && result.length > 0) {
    return { success: true, user: result };
  } else {
    return { success: false, message: 'No rows found' };
  }
  } catch (error) {
    throw new Error(`Error checking login: ${error.message}`);
  }
};

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