-- Backfill default data scopes by role for all existing users/modules
-- Safe after 030_dashboard_production_hardening.sql

INSERT INTO user_data_scopes (tenant_id, user_id, module_name, scope_type)
SELECT
    u.tenant_id,
    u.id,
    m.module_name,
    CASE
        WHEN u.role IN ('owner', 'admin') THEN 'all'
        WHEN u.role = 'manager' THEN 'team'
        ELSE 'own'
    END AS scope_type
FROM users u
CROSS JOIN (
    SELECT 'dashboard' AS module_name
    UNION ALL SELECT 'contacts'
    UNION ALL SELECT 'leads'
    UNION ALL SELECT 'activities'
    UNION ALL SELECT 'projects'
    UNION ALL SELECT 'pipeline'
    UNION ALL SELECT 'automations'
    UNION ALL SELECT 'communications'
    UNION ALL SELECT 'audit'
    UNION ALL SELECT 'billing'
    UNION ALL SELECT 'settings'
    UNION ALL SELECT 'users'
    UNION ALL SELECT 'teams'
    UNION ALL SELECT 'rbac'
    UNION ALL SELECT 'invitations'
    UNION ALL SELECT 'approvals'
    UNION ALL SELECT 'security'
    UNION ALL SELECT 'delegations'
    UNION ALL SELECT 'devices'
    UNION ALL SELECT 'api-docs'
    UNION ALL SELECT 'reports'
    UNION ALL SELECT 'customization'
    UNION ALL SELECT 'integrations'
    UNION ALL SELECT 'operations'
    UNION ALL SELECT 'onboarding'
) m
LEFT JOIN user_data_scopes s
    ON s.tenant_id = u.tenant_id
   AND s.user_id = u.id
   AND s.module_name = m.module_name
WHERE s.id IS NULL;
