-- Add Emergency Access permission for standalone user dashboard.
-- Run this in the central auth database.

INSERT INTO programs (program_code, program_name, is_active, created_at, updated_at)
VALUES ('ACCESS_DASHBOARD', 'Access Dashboard', 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE program_name = VALUES(program_name), is_active = 1, updated_at = NOW();

SET @access_program_id := (SELECT id FROM programs WHERE program_code = 'ACCESS_DASHBOARD' LIMIT 1);

INSERT INTO permissions (program_id, permission_key, permission_name, permission_group, sort_order, is_active, created_at, updated_at)
VALUES
(@access_program_id, 'security_emergency_manage', 'Manage Emergency MFA/User Recovery', 'Security', 445, 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE
permission_name = VALUES(permission_name),
permission_group = VALUES(permission_group),
sort_order = VALUES(sort_order),
is_active = 1,
updated_at = NOW();

-- Give this permission to Super Admin role automatically.
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
INNER JOIN permissions p ON p.program_id = @access_program_id AND p.permission_key = 'security_emergency_manage'
WHERE r.role_key = 'super_admin';
