-- Add Organization Permissions to the Database
-- Run this script to add the required permissions for the Organization API

-- Insert organization permissions
INSERT IGNORE INTO `permissions` (`name`, `description`, `resource`, `action`, `is_active`, `created_at`, `updated_at`) VALUES
  ('organization.create', 'Create new organizations', 'organization', 'create', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
  ('organization.read', 'View organization information', 'organization', 'read', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
  ('organization.update', 'Update organization information', 'organization', 'update', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
  ('organization.delete', 'Delete organizations', 'organization', 'delete', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
  ('organization.manage', 'Manage organizations (full access)', 'organization', 'manage', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

-- Get the permission IDs (you'll need these for role assignments)
SELECT id, name, description FROM permissions WHERE resource = 'organization' ORDER BY id;

-- Example: Assign all organization permissions to Super Admin role (role_id = 1)
-- Uncomment the following lines to execute:

-- INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`, `created_at`)
-- SELECT 1, id, CURRENT_TIMESTAMP FROM permissions WHERE resource = 'organization';

-- Example: Assign read-only organization permissions to User role (role_id = 3)
-- Uncomment the following lines to execute:

-- INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`, `created_at`)
-- SELECT 3, id, CURRENT_TIMESTAMP FROM permissions WHERE resource = 'organization' AND action = 'read';

-- Verify the permissions were added
SELECT 
  p.id,
  p.name,
  p.description,
  p.resource,
  p.action,
  p.is_active,
  COUNT(rp.role_id) as assigned_to_roles
FROM permissions p
LEFT JOIN role_permissions rp ON p.id = rp.permission_id
WHERE p.resource = 'organization'
GROUP BY p.id, p.name, p.description, p.resource, p.action, p.is_active
ORDER BY p.id;

