const logger = require("../../../../../handlers/logger");
const db = require("../../../../../managers/dbConfig");
const servicesCatalogQueries = require("../queries/servicesCatalogQueries");

// ✅ Create a new service
const createService = async (req, res) => {
  const { name, price, description } = req.body;
  if (!name || price == null)
    return res.status(400).json({ error: "Name and price are required." });

  try {
    const [result] = await db.execute(servicesCatalogQueries.insertService, [
      name,
      price,
      description,
    ]);
    res.status(201).json({ message: "Service added", id: result.insertId });
  } catch (err) {
    logger.error("Create service error:", err.message);
    res.status(500).json({ error: "Failed to create service." });
  }
};

// 📥 Get all services
const getAllServices = async (req, res) => {
  try {
    const [rows] = await db.execute(servicesCatalogQueries.getAllServices);
    res.json(rows);
  } catch (err) {
    logger.error("Fetch services error:", err.message);
    res.status(500).json({ error: "Failed to fetch services." });
  }
};

// 📥 Get service by ID
const getServiceById = async (req, res) => {
  try {
    const [rows] = await db.execute(servicesCatalogQueries.getServiceById, [
      req.params.id,
    ]);
    if (rows.length === 0)
      return res.status(404).json({ error: "Service not found." });
    res.json(rows[0]);
  } catch (err) {
    logger.error("Get service error:", err.message);
    res.status(500).json({ error: "Failed to fetch service." });
  }
};

// ♻️ Update service
const updateService = async (req, res) => {
  const { name, price, description, updated_by } = req.body;
  if (name == "" && price == "" && description == "")
    return res.status(400).json({ error: "All fields can NOT be empty" });

  try {
    await db.execute(servicesCatalogQueries.updateService, [
      name,
      price,
      description,

      updated_by,
      req.params.id,
    ]);
    res.json({ message: "Service updated." });
  } catch (err) {
    logger.error("Update service error:", err);
    res.status(500).json({ error: "Failed to update service." });
  }
};

// ❌ Delete service
const deleteService = async (req, res) => {
  try {
    await db.execute(servicesCatalogQueries.deleteService, [req.params.id]);
    res.json({ message: "Service deleted." });
  } catch (err) {
    logger.error("Delete service error:", err.message);
    res.status(500).json({ error: "Failed to delete service." });
  }
};

// 🔍 Search services (for typeahead)
const searchServices = async (req, res) => {
  try {
    const term = req.query.q;
    // console.log("Search term:", term);
    const [results] = await db.execute(
      servicesCatalogQueries.searchServicesByName,
      [`%${term}%`]
    );
    for (const result of results) {
      // result.price = parseFloat(result.price).toFixed(2); // Format price to 2 decimal places
      // console.log(typeof result.price);
    }
    //console.log("Search results:", results);
    res.json(results);
  } catch (err) {
    logger.error("Search services error:", err);
    res.status(500).json({ error: "Search failed." });
  }
};

module.exports = {
  createService,
  getAllServices,
  getServiceById,
  updateService,
  deleteService,
  searchServices,
};
