-- ============================================================
-- NICC Admin Menu - Migracion 0005
-- Reestructurar permisos:
--   - 'manager' es el rol con mas privilegios (acceso total)
--   - 'admin' tiene acceso limitado (NO a Sistema, Herramientas, Config Menu)
--   - 'superuser' se convierte en permisos de 'manager'
-- ============================================================

-- Paso 1: Copiar permisos de superuser a manager (para que manager tenga todo)
INSERT OR REPLACE INTO admin_menu_permissions (item_id, role, can_view, can_execute)
SELECT item_id, 'manager', 1, 1 FROM admin_menu_permissions WHERE role = 'superuser';

-- Paso 2: Manager tiene acceso a TODOS los items
INSERT OR REPLACE INTO admin_menu_permissions (item_id, role, can_view, can_execute)
SELECT id, 'manager', 1, 1 FROM admin_menu_items;

-- Paso 3: Admin NO tiene acceso a Sistema y Configuracion
UPDATE admin_menu_permissions
SET can_view = 0, can_execute = 0
WHERE role = 'admin'
AND item_id IN (
    SELECT i.id FROM admin_menu_items i
    JOIN admin_menu_categories c ON i.category_id = c.id
    WHERE c.code = 'system'
);

-- Paso 4: Admin NO tiene acceso a Herramientas
UPDATE admin_menu_permissions
SET can_view = 0, can_execute = 0
WHERE role = 'admin'
AND item_id IN (
    SELECT i.id FROM admin_menu_items i
    JOIN admin_menu_categories c ON i.category_id = c.id
    WHERE c.code = 'tools'
);

-- Paso 5: Admin NO tiene acceso a Configurar Menu NICC
UPDATE admin_menu_permissions
SET can_view = 0, can_execute = 0
WHERE role = 'admin'
AND item_id IN (
    SELECT id FROM admin_menu_items WHERE code = 'niccadminmenu'
);

-- Paso 6: Admin SI tiene acceso a Usuarios y Permisos
UPDATE admin_menu_permissions
SET can_view = 1, can_execute = 1
WHERE role = 'admin'
AND item_id IN (
    SELECT i.id FROM admin_menu_items i
    JOIN admin_menu_categories c ON i.category_id = c.id
    WHERE c.code = 'users'
);

-- Paso 7: Admin SI tiene acceso a Modulos NICC
UPDATE admin_menu_permissions
SET can_view = 1, can_execute = 1
WHERE role = 'admin'
AND item_id IN (
    SELECT i.id FROM admin_menu_items i
    JOIN admin_menu_categories c ON i.category_id = c.id
    WHERE c.code = 'nicc_modules'
);

-- Fin de migracion
SELECT 1;
