-- ============================================================================
-- Grant All Modules to Dev Team Group
-- ============================================================================
-- Purpose: Give Dev Team access to all modules in the system
-- This includes HR, Finance, Payroll, Fleet, Packaging, QA, and all others
-- ============================================================================

-- Step 1: Delete all existing Dev Team permissions
DELETE FROM group_module_permissions 
WHERE group_id = '0194a8b2-eeee-7123-8123-123456789ace'::uuid;

-- Step 2: Grant Dev Team access to ALL modules
INSERT INTO group_module_permissions (group_id, module_id, action)
SELECT 
    '0194a8b2-eeee-7123-8123-123456789ace'::uuid AS group_id,  -- Dev Team
    m.module_id,
    'allow' AS action
FROM modules m
WHERE m.module_id IS NOT NULL
ON CONFLICT DO NOTHING;

-- Step 3: Verify grants were created
SELECT 
    'Dev Team Permissions Summary' as info,
    COUNT(*) as total_modules_granted
FROM group_module_permissions gmp
JOIN groups g ON g.group_id = gmp.group_id
WHERE g.name = 'Dev Team';

-- Step 4: Show all granted modules for Dev Team
SELECT 
    g.name AS group_name,
    m.name AS module_name,
    m.icon,
    m.description,
    gmp.action
FROM group_module_permissions gmp
JOIN groups g ON g.group_id = gmp.group_id
JOIN modules m ON m.module_id = gmp.module_id
WHERE g.name = 'Dev Team'
ORDER BY m.name;

-- Success message
DO $$
DECLARE
    module_count INTEGER;
BEGIN
    SELECT COUNT(*) INTO module_count
    FROM group_module_permissions gmp
    JOIN groups g ON g.group_id = gmp.group_id
    WHERE g.name = 'Dev Team';
    
    RAISE NOTICE '============================================================================';
    RAISE NOTICE 'SUCCESS: Dev Team granted access to % modules', module_count;
    RAISE NOTICE 'This includes all HR, Finance, Payroll, Fleet, Packaging, QA modules';
    RAISE NOTICE '============================================================================';
END $$;
