-- Add role_id column
ALTER TABLE `role_permissions` ADD COLUMN `role_id` INT(11) NULL AFTER `id`;

-- Update role_id from existing role name
UPDATE `role_permissions` rp
JOIN `roles` r ON rp.role = r.name
SET rp.role_id = r.id;

-- Make role_id not nullable
ALTER TABLE `role_permissions` MODIFY `role_id` INT(11) NOT NULL;

-- Drop the old unique key
ALTER TABLE `role_permissions` DROP INDEX `role_resource_action`;

-- Drop the old role column
ALTER TABLE `role_permissions` DROP COLUMN `role`;

-- Add new unique key with role_id
ALTER TABLE `role_permissions` ADD UNIQUE KEY `role_resource_action` (`role_id`, `resource`, `action`);

-- Add foreign key to roles table
ALTER TABLE `role_permissions` ADD CONSTRAINT `fk_permission_role` FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
