-- MSIN-4401 — Permission page hub : Tableau de bord
-- Prérequis : MSIN-4401-eve-acces-v2-pages-niveau1.sql (groupes page_hub)
-- Idempotent. Safe pilote. Ne touche pas au legacy.

SET NAMES utf8mb4;

INSERT INTO `inscriptions_eve_permissions`
  (`perm_key`, `perm_group`, `perm_scope`, `perm_label_fr`, `perm_label_en`,
   `perm_description_fr`, `perm_description_en`, `perm_phase`, `perm_actif`, `perm_tri`)
VALUES
  ('hub.dashboard', 'page_hub', 'page',
   'Tableau de bord', 'Dashboard',
   'Bouton Tableau de bord du hub (inscrits, places, revenus, epreuves)',
   'Hub dashboard button (registrations, spots, revenue, races)',
   2, 1, 5)
ON DUPLICATE KEY UPDATE
  `perm_group` = VALUES(`perm_group`),
  `perm_scope` = VALUES(`perm_scope`),
  `perm_label_fr` = VALUES(`perm_label_fr`),
  `perm_label_en` = VALUES(`perm_label_en`),
  `perm_description_fr` = VALUES(`perm_description_fr`),
  `perm_description_en` = VALUES(`perm_description_en`),
  `perm_phase` = VALUES(`perm_phase`),
  `perm_actif` = VALUES(`perm_actif`),
  `perm_tri` = VALUES(`perm_tri`);

/* Kits ops : dashboard oui */
INSERT INTO inscriptions_eve_role_permissions (role_id, perm_key)
SELECT r.role_id, 'hub.dashboard'
FROM inscriptions_eve_roles r
WHERE r.role_code = 'gestion_ops'
ON DUPLICATE KEY UPDATE perm_key = VALUES(perm_key);

/* Kits statut / readonly / bib : pas de dashboard (retire si present) */
DELETE erp FROM inscriptions_eve_role_permissions erp
INNER JOIN inscriptions_eve_roles r ON r.role_id = erp.role_id
WHERE erp.perm_key = 'hub.dashboard'
  AND r.role_code IN ('gestion_statut', 'gestion_readonly', 'bib_ops', 'qr_debug');

/* Owner : resync permissions actives (inclut hub.dashboard) */
DELETE erp FROM inscriptions_eve_role_permissions erp
INNER JOIN inscriptions_eve_roles r ON r.role_id = erp.role_id
WHERE r.role_code = 'owner';

INSERT INTO inscriptions_eve_role_permissions (role_id, perm_key)
SELECT r.role_id, p.perm_key
FROM inscriptions_eve_roles r
CROSS JOIN inscriptions_eve_permissions p
WHERE r.role_code = 'owner'
  AND p.perm_actif = 1;
