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

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

  try {
    const locais = await localService.getAllLocais(queryParams);
    res.json(locais);
  } catch (error) {
    logger.error(`Error getting all locais: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

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


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

const updateLocal = async (req, res) => {
  const { id } = req.params;
  const { body } = req;
  try {
    const updatedLocal = await localService.updateLocal(id, body);
    if (!updatedLocal) {
      return res.status(404).json({ error: "Local not found" });
    }
    res.json(updatedLocal);
  } catch (error) {     
    logger.error(`Error updating local: ${error.message}`);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

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

module.exports = {
  getAllLocais,
  getLocalById,
  createLocal,
  updateLocal,
  deleteLocal,
};
