-- ============================================================
-- ROLE LOCK-DOWN ("limited roles, for time being").
-- Only SysAdmin can create/change reports or touch admin areas.
-- Everyone else gets a minimal view:
--     Manager     -> Dashboard (overall clients) + Reports browser + Notifications
--     Supervisor  -> Reports browser + Notifications
--     Client / others -> Reports browser + Notifications
-- Idempotent — safe to re-run. Reversible by re-running schema.sql + seed-additional-roles.sql.
--   phpMyAdmin: select your DB, paste, Go.   CLI: mysql -u <u> -p <db> < sql/seed-role-lockdown.sql
-- ============================================================

-- 1) Permission that unlocks the overall dashboard (Manager + SysAdmin only).
INSERT INTO `permissions` (`code`,`label`,`group_name`,`description`,`created_at`,`updated_at`) VALUES
  ('dashboard.view','View Dashboard','reports','Access the overall clients dashboard',NOW(),NOW())
ON DUPLICATE KEY UPDATE `label`=VALUES(`label`),`updated_at`=NOW();

-- 2) Wipe every NON-sysadmin role's permissions (clean slate = "remove rest of access").
DELETE rp FROM `role_permissions` rp
  JOIN `roles` r ON r.id = rp.role_id
 WHERE r.code <> 'sysadmin';

-- 3) Manager: overall dashboard + reports browser (view detail + download so reports are usable)
--    + internal user management (create/manage internal staff).
INSERT IGNORE INTO `role_permissions` (`role_id`,`permission_id`)
  SELECT r.id, p.id FROM `roles` r JOIN `permissions` p
    ON p.code IN ('dashboard.view','report.view','report.view_detail','report.download',
                  'user.internal.view','user.internal.manage')
  WHERE r.code = 'manager';

-- 4) Supervisor + Client + every other non-sysadmin role: reports browser only.
INSERT IGNORE INTO `role_permissions` (`role_id`,`permission_id`)
  SELECT r.id, p.id FROM `roles` r JOIN `permissions` p
    ON p.code IN ('report.view','report.view_detail','report.download')
  WHERE r.code IN ('supervisor','client_viewer','client_admin',
                   'developer','vertical_manager','client_manager','process_lead',
                   'analyst','auditor','report_controller','user');

-- 4b) Supervisor + Manager can REPLACE/upload data into EXISTING reports (not create new ones).
INSERT IGNORE INTO `role_permissions` (`role_id`,`permission_id`)
  SELECT r.id, p.id FROM `roles` r JOIN `permissions` p
    ON p.code IN ('report.upload','report.replace_all')
  WHERE r.code IN ('supervisor','manager');

-- 5) Make sure SysAdmin still holds EVERY permission (incl. the new dashboard.view).
INSERT IGNORE INTO `role_permissions` (`role_id`,`permission_id`)
  SELECT r.id, p.id FROM `roles` r CROSS JOIN `permissions` p
  WHERE r.code = 'sysadmin';
