-- =============================================================
-- corregir_permisos_administrador_20260828.sql
-- =============================================================
-- Correccion puntual para bases ya instaladas.
-- Elimina la tabla permisos y la recrea desde cero.
-- Luego carga permisos completos solo para el rol_id = 1.

SET FOREIGN_KEY_CHECKS = 0;

START TRANSACTION;

DROP TABLE IF EXISTS permisos;

CREATE TABLE permisos (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    rol_id BIGINT UNSIGNED NOT NULL,
    modulo_id BIGINT UNSIGNED NOT NULL,
    accion_id BIGINT UNSIGNED NOT NULL,
    permitido TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NULL,
    UNIQUE KEY uq_permiso (rol_id, modulo_id, accion_id),
    KEY idx_permisos_rol (rol_id),
    KEY idx_permisos_modulo (modulo_id),
    KEY idx_permisos_accion (accion_id),
    CONSTRAINT fk_permisos_rol FOREIGN KEY (rol_id) REFERENCES roles(id),
    CONSTRAINT fk_permisos_modulo FOREIGN KEY (modulo_id) REFERENCES modulos(id),
    CONSTRAINT fk_permisos_accion FOREIGN KEY (accion_id) REFERENCES acciones(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO permisos (rol_id, modulo_id, accion_id, permitido, created_at)
SELECT DISTINCT
    1,
    m.id,
    a.id,
    1,
    NOW()
FROM modulos m
INNER JOIN acciones a
        ON a.estado = 1
WHERE m.estado = 1
  AND m.deleted_at IS NULL;

COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

-- Fin de la correccion.
