SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

ALTER TABLE `access_attempts`
  MODIFY `tipo` ENUM('login','logout','recuperacion','restablecer','mfa','usuario_crear','usuario_actualizar','usuario_toggle','usuario_forzar_clave') NOT NULL;

CREATE TABLE IF NOT EXISTS `usuario_roles` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `usuario_id` BIGINT UNSIGNED NOT NULL,
  `rol_codigo` VARCHAR(80) NOT NULL,
  `rol_nombre` VARCHAR(120) NOT NULL,
  `principal` TINYINT(1) NOT NULL DEFAULT 0,
  `estado` ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  `asignado_por` BIGINT UNSIGNED NULL,
  `creado_en` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `actualizado_en` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_usuario_roles_usuario_rol` (`usuario_id`, `rol_codigo`),
  KEY `idx_usuario_roles_usuario_estado` (`usuario_id`, `estado`),
  KEY `idx_usuario_roles_rol` (`rol_codigo`),
  KEY `idx_usuario_roles_principal` (`principal`),
  CONSTRAINT `fk_usuario_roles_usuario` FOREIGN KEY (`usuario_id`) REFERENCES `usuarios` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `usuario_roles` (`usuario_id`, `rol_codigo`, `rol_nombre`, `principal`, `estado`, `asignado_por`, `creado_en`, `actualizado_en`)
SELECT u.id, 'superadmin_total', 'Control total', 1, 'activo', u.id, NOW(), NOW()
FROM `usuarios` u
LEFT JOIN `usuario_roles` ur ON ur.usuario_id = u.id AND ur.rol_codigo = 'superadmin_total'
WHERE u.tipo_usuario = 'superadmin' AND ur.id IS NULL;

SET FOREIGN_KEY_CHECKS = 1;
