UPDATE base_model_catalog
SET default_snapshot = default_snapshot
  || jsonb_build_object(
    'modelType', CASE
      WHEN jsonb_typeof(default_snapshot -> 'modelType') = 'array' THEN default_snapshot -> 'modelType'
      WHEN COALESCE(default_snapshot ->> 'modelType', '') <> '' THEN jsonb_build_array(default_snapshot ->> 'modelType')
      WHEN jsonb_typeof(capabilities -> 'originalTypes') = 'array' THEN capabilities -> 'originalTypes'
      ELSE jsonb_build_array(model_type)
    END,
    'modelAlias', COALESCE(default_snapshot ->> 'modelAlias', default_snapshot ->> 'displayName', display_name)
  )
WHERE catalog_type = 'system'
  AND COALESCE(default_snapshot, '{}'::jsonb) <> '{}'::jsonb;

CREATE OR REPLACE FUNCTION fill_system_base_model_default_snapshot()
RETURNS trigger AS $$
BEGIN
  IF NEW.catalog_type = 'system' AND NEW.default_snapshot IS NULL THEN
    NEW.default_snapshot = jsonb_build_object(
      'providerKey', NEW.provider_key,
      'canonicalModelKey', NEW.canonical_model_key,
      'providerModelName', NEW.provider_model_name,
      'modelType', CASE
        WHEN jsonb_typeof(NEW.capabilities -> 'originalTypes') = 'array' THEN NEW.capabilities -> 'originalTypes'
        ELSE jsonb_build_array(NEW.model_type)
      END,
      'modelAlias', NEW.display_name,
      'capabilities', NEW.capabilities,
      'baseBillingConfig', NEW.base_billing_config,
      'defaultRateLimitPolicy', NEW.default_rate_limit_policy,
      'pricingRuleSetId', COALESCE(NEW.pricing_rule_set_id::text, ''),
      'runtimePolicySetId', COALESCE(NEW.runtime_policy_set_id::text, ''),
      'runtimePolicyOverride', NEW.runtime_policy_override,
      'metadata', NEW.metadata,
      'pricingVersion', NEW.pricing_version,
      'status', NEW.status
    );
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
