-- Migration 065: Sync legacy User.company_id to user_companies table
-- For all users with company_id set but missing user_companies record

INSERT INTO user_companies (user_id, company_id, role, is_primary, created_at, updated_at)
SELECT u.id, u.company_id, 'MANAGER', true, NOW(), NOW()
FROM users u
WHERE u.company_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM user_companies uc
    WHERE uc.user_id = u.id AND uc.company_id = u.company_id
  );
