-- Phase 5 permission repair for existing installations.
-- Safe to run multiple times. It only adds missing role/permission links.

INSERT INTO roles (name, display_name) VALUES
('SUPER_ADMIN', 'Super Administrator'),
('ADMIN', 'Administrator'),
('THERAPIST', 'Therapist')
ON DUPLICATE KEY UPDATE display_name = VALUES(display_name);

INSERT INTO permissions (name, display_name) VALUES
('users.view', 'View users'),
('users.create', 'Create users'),
('users.edit', 'Edit users'),
('users.disable', 'Disable users'),
('settings.manage', 'Manage settings'),
('audit.view', 'View audit logs')
ON DUPLICATE KEY UPDATE display_name = VALUES(display_name);

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p
WHERE r.name = 'SUPER_ADMIN'
  AND p.name IN ('users.view', 'users.create', 'users.edit', 'users.disable', 'settings.manage', 'audit.view');

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p
WHERE r.name = 'ADMIN';
