-- Add permissions using the correct Directus permissions structure
-- First, let's see what policies exist for the admin role
SELECT 'Existing policies for admin role:' as info;
SELECT id, name FROM directus_policies WHERE name ILIKE '%admin%' OR name ILIKE '%administrator%';

-- Create a policy for admin role to access moderation collections
INSERT INTO directus_policies (name, description)
SELECT 'Admin Moderation Access', 'Full access to moderation collections for administrators'
WHERE NOT EXISTS (
    SELECT 1 FROM directus_policies WHERE name = 'Admin Moderation Access'
);

-- Get the policy ID
SELECT 'Created policy ID:' as info;
SELECT id, name FROM directus_policies WHERE name = 'Admin Moderation Access';

-- Add permissions for the policy
INSERT INTO directus_permissions (collection, action, permissions, policy)
SELECT 
    'moderation_flags',
    '*',
    '{"_and": [{"_system": {"_eq": true}}]}',
    (SELECT id FROM directus_policies WHERE name = 'Admin Moderation Access' LIMIT 1)
WHERE NOT EXISTS (
    SELECT 1 FROM directus_permissions 
    WHERE collection = 'moderation_flags' 
    AND policy = (SELECT id FROM directus_policies WHERE name = 'Admin Moderation Access' 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 = 'Admin Moderation Access' LIMIT 1)
WHERE NOT EXISTS (
    SELECT 1 FROM directus_permissions 
    WHERE collection = 'user_status_history' 
    AND policy = (SELECT id FROM directus_policies WHERE name = 'Admin Moderation Access' LIMIT 1)
);

-- Assign the policy to the admin role
INSERT INTO directus_access (role, policy)
SELECT 
    (SELECT id FROM directus_roles WHERE name = 'Administrator' LIMIT 1),
    (SELECT id FROM directus_policies WHERE name = 'Admin Moderation Access' 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 = 'Admin Moderation Access' LIMIT 1)
);

SELECT 'Permissions setup completed:' 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 = 'Admin Moderation Access';
