-- Sanitize invalid user_data_scopes values
-- Safe after 031_user_data_scopes_default_backfill.sql

UPDATE user_data_scopes s
INNER JOIN users u
    ON u.id = s.user_id
   AND u.tenant_id = s.tenant_id
SET s.scope_type = CASE
    WHEN u.role IN ('owner', 'admin') THEN 'all'
    WHEN u.role = 'manager' THEN 'team'
    ELSE 'own'
END
WHERE s.scope_type IS NULL
   OR s.scope_type NOT IN ('own', 'team', 'all');
