-- ====================================================================
-- Per-staff 2FA switch (2026-09-23)
--   • New permission `employees:manage-2fa` (granted to super_admin): whoever
--     has it can turn 2FA on/off for staff. The switch is
--     employees.two_fa_enabled (1 = code by email at every sign-in).
--   • Super admins ALWAYS use 2FA, whatever the column says.
--   • The first run keeps today's behaviour (2FA on for everyone) by turning
--     the column on for all employees. Re-running doesn't touch it again,
--     so later on/off choices are kept.
--   • New employees start with 2FA on (column default 1).
-- Plain statements only, safe to run more than once.
-- ====================================================================

SET NAMES utf8mb4;

SET @first_run = (SELECT COUNT(*) = 0 FROM `permissions` WHERE `name` = 'employees:manage-2fa');

UPDATE `employees` SET `two_fa_enabled` = 1 WHERE @first_run = 1;

ALTER TABLE `employees` ALTER COLUMN `two_fa_enabled` SET DEFAULT 1;

INSERT IGNORE INTO `permissions` (`id`, `name`, `module`, `action`) VALUES
  (UUID(), 'employees:manage-2fa', 'employees', 'manage_2fa');

INSERT IGNORE INTO `role_permissions` (`id`, `role_id`, `permission_id`)
SELECT UUID(), r.id, p.id
FROM `roles` r
JOIN `permissions` p ON p.name = 'employees:manage-2fa'
WHERE r.name = 'super_admin';
