-- Purge legacy hems_duty_roster.* permissions.
-- Safe flow:
-- 1) Ensure canonical duty_roster.* permissions exist.
-- 2) Grant canonical permission to any role that still has legacy permission.
-- 3) Remove legacy role_permissions rows.
-- 4) Remove legacy permission rows.

INSERT INTO permissions (id, name, `key`, description, requires_pin, created_at, updated_at)
SELECT UUID_TO_BIN(UUID(), true), 'Create Duty Roster', 'duty_roster.create', 'Create duty roster', 0, UTC_TIMESTAMP(), UTC_TIMESTAMP()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE `key` = 'duty_roster.create');

INSERT INTO permissions (id, name, `key`, description, requires_pin, created_at, updated_at)
SELECT UUID_TO_BIN(UUID(), true), 'Read Duty Roster', 'duty_roster.read', 'Read duty roster', 0, UTC_TIMESTAMP(), UTC_TIMESTAMP()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE `key` = 'duty_roster.read');

INSERT INTO permissions (id, name, `key`, description, requires_pin, created_at, updated_at)
SELECT UUID_TO_BIN(UUID(), true), 'Update Duty Roster', 'duty_roster.update', 'Update duty roster', 0, UTC_TIMESTAMP(), UTC_TIMESTAMP()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE `key` = 'duty_roster.update');

INSERT INTO permissions (id, name, `key`, description, requires_pin, created_at, updated_at)
SELECT UUID_TO_BIN(UUID(), true), 'Delete Duty Roster', 'duty_roster.delete', 'Delete duty roster', 0, UTC_TIMESTAMP(), UTC_TIMESTAMP()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE `key` = 'duty_roster.delete');

INSERT INTO role_permissions (id, role_id, permission_id, created_at, updated_at)
SELECT
  UUID_TO_BIN(UUID(), true),
  rp.role_id,
  p_new.id,
  UTC_TIMESTAMP(),
  UTC_TIMESTAMP()
FROM role_permissions rp
JOIN permissions p_old ON p_old.id = rp.permission_id
JOIN permissions p_new ON p_new.`key` = CONCAT('duty_roster.', SUBSTRING_INDEX(p_old.`key`, '.', -1))
LEFT JOIN role_permissions rp_existing ON rp_existing.role_id = rp.role_id AND rp_existing.permission_id = p_new.id
WHERE p_old.`key` IN (
  'hems_duty_roster.create',
  'hems_duty_roster.read',
  'hems_duty_roster.update',
  'hems_duty_roster.delete'
)
AND rp_existing.id IS NULL;

DELETE rp
FROM role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
WHERE p.`key` IN (
  'hems_duty_roster.create',
  'hems_duty_roster.read',
  'hems_duty_roster.update',
  'hems_duty_roster.delete'
);

DELETE FROM permissions
WHERE `key` IN (
  'hems_duty_roster.create',
  'hems_duty_roster.read',
  'hems_duty_roster.update',
  'hems_duty_roster.delete'
);
