-- Tabla de estados de agente (simple y eficiente)
CREATE TABLE IF NOT EXISTS mesacontrol_agente_estado (
  id INT AUTO_INCREMENT PRIMARY KEY,
  login VARCHAR(64) NOT NULL,
  estado ENUM('logout','disponible','pausa','baño','comida','entrenamiento') NOT NULL DEFAULT 'logout',
  session_id VARCHAR(128) DEFAULT NULL,
  last_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_seen   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  user_agent  VARCHAR(255) DEFAULT NULL,
  ip          VARCHAR(64)  DEFAULT NULL,
  is_active   TINYINT(1) NOT NULL DEFAULT 0,
  UNIQUE KEY uk_login (login),
  KEY idx_seen (last_seen)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- (Opcional) Evento MySQL para dar logout si no hay heartbeat > 2 min
-- Requiere: SET GLOBAL event_scheduler = ON;
DROP EVENT IF EXISTS ev_mesacontrol_autologout;
CREATE EVENT ev_mesacontrol_autologout
ON SCHEDULE EVERY 1 MINUTE
DO
  UPDATE mesacontrol_agente_estado
     SET estado='logout', is_active=0
   WHERE is_active=1
     AND TIMESTAMPDIFF(SECOND, last_seen, NOW()) > 120;

-- Vista opcional
CREATE OR REPLACE VIEW vw_mesacontrol_agentes_estado AS
SELECT 
  e.login,
  COALESCE(u.name, e.login) AS nombre,
  e.estado,
  e.is_active,
  e.session_id,
  e.last_change,
  e.last_seen,
  e.user_agent,
  e.ip
FROM mesacontrol_agente_estado e
LEFT JOIN sec_users u ON u.login = e.login;
