-- Use the existing Administrator policy to add moderation permissions
-- Get the existing Administrator policy ID
SELECT 'Administrator policy:' as info;
SELECT id, name FROM directus_policies WHERE name = 'Administrator';

-- Add permissions for moderation collections to the existing Administrator policy
INSERT INTO directus_permissions (collection, action, permissions, policy)
SELECT 
    'moderation_flags',
    '*',
    '{"_and": [{"_system": {"_eq": true}}]}',
    (SELECT id FROM directus_policies WHERE name = 'Administrator' LIMIT 1)
WHERE NOT EXISTS (
    SELECT 1 FROM directus_permissions 
    WHERE collection = 'moderation_flags' 
    AND policy = (SELECT id FROM directus_policies WHERE name = 'Administrator' LIMIT 1)
);

INSERT INTO directus_permissions (collection, action, permissions, policy)
SELECT 
    'user_status_history',
    '*',
    '{"_and": [{"_system": {"_eq": true}}]}',
    (SELECT id FROM directus_policies WHERE name = 'Administrator' LIMIT 1)
WHERE NOT EXISTS (
    SELECT 1 FROM directus_permissions 
    WHERE collection = 'user_status_history' 
    AND policy = (SELECT id FROM directus_policies WHERE name = 'Administrator' LIMIT 1)
);

-- Check if admin role is already assigned to Administrator policy
SELECT 'Admin role assignments:' as info;
SELECT role, policy FROM directus_access WHERE role = (SELECT id FROM directus_roles WHERE name = 'Administrator' LIMIT 1);

-- If not assigned, assign it
INSERT INTO directus_access (role, policy)
SELECT 
    (SELECT id FROM directus_roles WHERE name = 'Administrator' LIMIT 1),
    (SELECT id FROM directus_policies WHERE name = 'Administrator' LIMIT 1)
WHERE NOT EXISTS (
    SELECT 1 FROM directus_access 
    WHERE role = (SELECT id FROM directus_roles WHERE name = 'Administrator' LIMIT 1)
    AND policy = (SELECT id FROM directus_policies WHERE name = 'Administrator' LIMIT 1)
);

SELECT 'Final permissions check:' as info;
SELECT p.name as policy_name, pe.collection, pe.action 
FROM directus_policies p
JOIN directus_permissions pe ON p.id = pe.policy
WHERE p.name = 'Administrator' AND pe.collection IN ('moderation_flags', 'user_status_history');
