-- Migration: Sync user roles with is_admin flag
-- Date: 2026-02-01
-- Description: Ensures all users have proper role field based on is_admin and company membership
-- Part of: Role-based access control migration from is_admin to SystemRole

-- 1. Set ADMIN role for users with is_admin=true
UPDATE users
SET role = 'ADMIN'
WHERE is_admin = true AND (role IS NULL OR role != 'ADMIN');

-- 2. Set MEMBER role for non-admin users who have is_norda_member=true but no company
UPDATE users
SET role = 'MEMBER'
WHERE is_admin = false
  AND is_norda_member = true
  AND company_id IS NULL
  AND (role IS NULL OR role = 'UNAFFILIATED');

-- 3. Set EMPLOYEE role for non-admin users who have a company assigned
UPDATE users
SET role = 'EMPLOYEE'
WHERE is_admin = false
  AND company_id IS NOT NULL
  AND (role IS NULL OR role = 'UNAFFILIATED');

-- 4. Set UNAFFILIATED for remaining users without role
UPDATE users
SET role = 'UNAFFILIATED'
WHERE role IS NULL;

-- 5. Verify: Show role distribution after migration
-- SELECT role, COUNT(*) as count FROM users GROUP BY role ORDER BY role;
