ALTER TABLE gateway_oidc_sessions
  ADD COLUMN IF NOT EXISTS context_type text,
  ADD COLUMN IF NOT EXISTS issuer text,
  ADD COLUMN IF NOT EXISTS application_id text,
  ADD COLUMN IF NOT EXISTS subject text,
  ADD COLUMN IF NOT EXISTS tenant_id text;

UPDATE gateway_oidc_sessions session_record
SET context_type = 'tenant',
    issuer = binding.issuer,
    application_id = binding.application_id,
    subject = user_binding.subject,
    tenant_id = binding.external_tenant_id
FROM gateway_oidc_user_bindings user_binding
JOIN gateway_oidc_tenant_bindings binding
  ON binding.id = user_binding.tenant_binding_id
WHERE session_record.oidc_user_binding_id = user_binding.id
  AND session_record.context_type IS NULL;

ALTER TABLE gateway_oidc_sessions
  DROP CONSTRAINT IF EXISTS gateway_oidc_sessions_context_identity;

ALTER TABLE gateway_oidc_sessions
  ADD CONSTRAINT gateway_oidc_sessions_context_identity CHECK (
    context_type IS NULL
    OR (
      context_type IN ('platform', 'tenant')
      AND issuer IS NOT NULL
      AND issuer <> ''
      AND application_id IS NOT NULL
      AND application_id <> ''
      AND subject IS NOT NULL
      AND subject <> ''
      AND (
        (context_type = 'platform' AND tenant_id IS NULL)
        OR
        (context_type = 'tenant' AND tenant_id IS NOT NULL AND tenant_id <> '')
      )
    )
  );
