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

export async function getSettings(req, res, next) {
  try {
    const [rows] = await pool.query("SELECT clave, valor FROM configuracion");
    const settings = {};
    for (const r of rows) {
      settings[r.clave] = r.valor;
    }
    res.json({
      success: true,
      data: settings
    });
  } catch (err) {
    next(err);
  }
}

export async function updateSettings(req, res, next) {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const settings = req.body;

    for (const [clave, valor] of Object.entries(settings)) {
      await connection.query(
        `INSERT INTO configuracion (clave, valor)
         VALUES (:clave, :valor)
         ON DUPLICATE KEY UPDATE valor = :valor`,
        { clave, valor: valor !== null ? String(valor) : null }
      );
    }

    await connection.commit();
    res.json({
      success: true,
      message: "Configuración actualizada correctamente"
    });
  } catch (err) {
    await connection.rollback();
    next(err);
  } finally {
    connection.release();
  }
}
