-- D1: the portal's Settings/Users page shows who the tenant's first admin -- is. Stored at creation (POST /v1/tenants admin_email) or on the first -- IT_ADMIN/OWNER invite through POST /v1/tenants/{id}/invites. Nullable — -- sales-led tenants may not have an admin yet. ALTER TABLE tenants ADD COLUMN admin_email TEXT; -- Backfill from the audit trail: the first successful Keycloak invite per -- tenant is the first admin (createTenant emits keycloak.invite_sent with -- target_id = admin email) … UPDATE tenants t SET admin_email = a.target_id FROM ( SELECT DISTINCT ON (tenant_id) tenant_id, target_id FROM audit_log WHERE action = 'keycloak.invite_sent' AND target_type = 'user' AND tenant_id IS NOT NULL AND target_id <> '' ORDER BY tenant_id, created_at ASC, id ASC ) a WHERE a.tenant_id = t.id AND t.admin_email IS NULL; -- … and, where provisioning failed, from the admin_email the failure -- event recorded (the operator re-sent the invite by hand). UPDATE tenants t SET admin_email = a.admin_email FROM ( SELECT DISTINCT ON (tenant_id) tenant_id, metadata->>'admin_email' AS admin_email FROM audit_log WHERE action = 'keycloak.provision_failed' AND tenant_id IS NOT NULL AND COALESCE(metadata->>'admin_email', '') <> '' ORDER BY tenant_id, created_at ASC, id ASC ) a WHERE a.tenant_id = t.id AND t.admin_email IS NULL;