-- Migration: optimize menu loading performance
-- Created at: 2026-03-12

BEGIN;

-- 1) remove duplicate role-menu mapping rows to allow unique key
DELETE r1
FROM role_menu_permissions r1
JOIN role_menu_permissions r2
  ON r1.role_id = r2.role_id
 AND r1.menu_id = r2.menu_id
 AND r1.id > r2.id;

-- 2) speed up role-menu lookup and prevent duplicate permission rows
ALTER TABLE `role_menu_permissions`
  ADD UNIQUE KEY `uk_role_menu` (`role_id`, `menu_id`),
  ADD KEY `idx_rmp_role` (`role_id`),
  ADD KEY `idx_rmp_menu` (`menu_id`);

-- 3) speed up visible active menu ordering by parent/sort
ALTER TABLE `menus`
  ADD KEY `idx_menus_visible_tree` (`is_active`, `is_visible`, `parent_id`, `sort_order`, `menu_id`);

COMMIT;
