import { pool } from "../config/db.js";

function mapService(row) {
  return {
    id: row.id,
    serviceName: row.service_name,
    serviceCode: row.service_code,
    price: Number(row.price || 0),
    unit: row.unit,
    isActive: Boolean(row.is_active),
    createdAt: row.created_at
  };
}

export async function getServices(req, res, next) {
  try {
    const [rows] = await pool.query(
      "SELECT * FROM services ORDER BY service_name ASC"
    );
    res.json({
      success: true,
      data: rows.map(mapService)
    });
  } catch (err) {
    next(err);
  }
}

export async function getServiceById(req, res, next) {
  try {
    const { id } = req.params;
    const [rows] = await pool.query("SELECT * FROM services WHERE id = ?", [id]);

    if (!rows.length) {
      return res.status(404).json({
        success: false,
        message: "Servicio no encontrado"
      });
    }

    res.json({
      success: true,
      data: mapService(rows[0])
    });
  } catch (err) {
    next(err);
  }
}

export async function createService(req, res, next) {
  try {
    const { serviceName, serviceCode, price, unit = "lb", isActive = 1 } = req.body;

    if (!serviceName || !serviceCode || price === undefined) {
      return res.status(400).json({
        success: false,
        message: "Nombre, código y precio son requeridos"
      });
    }

    const [result] = await pool.query(
      `
      INSERT INTO services (service_name, service_code, price, unit, is_active, created_at)
      VALUES (:serviceName, :serviceCode, :price, :unit, :isActive, NOW())
      `,
      {
        serviceName,
        serviceCode,
        price,
        unit,
        isActive: isActive ? 1 : 0
      }
    );

    const [rows] = await pool.query("SELECT * FROM services WHERE id = ?", [result.insertId]);

    res.status(201).json({
      success: true,
      message: "Servicio creado correctamente",
      data: mapService(rows[0])
    });
  } catch (err) {
    next(err);
  }
}

export async function updateService(req, res, next) {
  try {
    const { id } = req.params;
    const { serviceName, serviceCode, price, unit, isActive } = req.body;

    const [existing] = await pool.query("SELECT id FROM services WHERE id = ?", [id]);
    if (!existing.length) {
      return res.status(404).json({
        success: false,
        message: "Servicio no encontrado"
      });
    }

    await pool.query(
      `
      UPDATE services
      SET
        service_name = :serviceName,
        service_code = :serviceCode,
        price = :price,
        unit = :unit,
        is_active = :isActive
      WHERE id = :id
      `,
      {
        id,
        serviceName,
        serviceCode,
        price,
        unit,
        isActive: isActive ? 1 : 0
      }
    );

    const [rows] = await pool.query("SELECT * FROM services WHERE id = ?", [id]);

    res.json({
      success: true,
      message: "Servicio actualizado correctamente",
      data: mapService(rows[0])
    });
  } catch (err) {
    next(err);
  }
}

export async function deleteService(req, res, next) {
  try {
    const { id } = req.params;

    const [existing] = await pool.query("SELECT id FROM services WHERE id = ?", [id]);
    if (!existing.length) {
      return res.status(404).json({
        success: false,
        message: "Servicio no encontrado"
      });
    }

    await pool.query("DELETE FROM services WHERE id = ?", [id]);

    res.json({
      success: true,
      message: "Servicio eliminado correctamente"
    });
  } catch (err) {
    next(err);
  }
}
