package repository import ( "context" "gorm.io/gorm" ) func ClearOrphanUserTenantMemberships(ctx context.Context, db *gorm.DB) (int64, error) { result := db.WithContext(ctx).Exec(` WITH orphan_users AS ( SELECT u.id FROM users AS u WHERE u.deleted_at IS NULL AND ( ( u.tenant_id IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM tenants AS t WHERE t.id = u.tenant_id AND t.deleted_at IS NULL ) ) OR ( NULLIF(BTRIM(u.company_code), '') IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM tenants AS t WHERE LOWER(t.slug) = LOWER(BTRIM(u.company_code)) AND t.deleted_at IS NULL ) ) OR EXISTS ( SELECT 1 FROM UNNEST(COALESCE(u.company_codes, ARRAY[]::text[])) AS code(value) WHERE NULLIF(BTRIM(code.value), '') IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM tenants AS t WHERE LOWER(t.slug) = LOWER(BTRIM(code.value)) AND t.deleted_at IS NULL ) ) ) ) UPDATE users AS u SET tenant_id = NULL, company_code = '', company_codes = NULL, updated_at = NOW() FROM orphan_users AS ou WHERE u.id = ou.id `) return result.RowsAffected, result.Error }