ALTER TABLE IF EXISTS base_model_catalog
  ADD COLUMN IF NOT EXISTS catalog_type text NOT NULL DEFAULT 'system',
  ADD COLUMN IF NOT EXISTS default_snapshot jsonb,
  ADD COLUMN IF NOT EXISTS customized_at timestamptz;

UPDATE base_model_catalog
SET catalog_type = CASE
  WHEN metadata ->> 'source' = 'server-main.integration-platform'
    OR metadata ? 'sourceProviderCode'
    OR metadata ? 'rawModel'
  THEN 'system'
  ELSE 'custom'
END;

UPDATE base_model_catalog
SET default_snapshot = jsonb_build_object(
  'providerKey', provider_key,
  'canonicalModelKey', canonical_model_key,
  'providerModelName', provider_model_name,
  'modelType', CASE
    WHEN jsonb_typeof(capabilities -> 'originalTypes') = 'array' THEN capabilities -> 'originalTypes'
    ELSE jsonb_build_array(model_type)
  END,
  'modelAlias', display_name,
  'capabilities', capabilities,
  'baseBillingConfig', base_billing_config,
  'defaultRateLimitPolicy', default_rate_limit_policy,
  'pricingRuleSetId', COALESCE(pricing_rule_set_id::text, ''),
  'runtimePolicySetId', COALESCE(runtime_policy_set_id::text, ''),
  'runtimePolicyOverride', runtime_policy_override,
  'metadata', metadata,
  'pricingVersion', pricing_version,
  'status', status
)
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;

DROP TRIGGER IF EXISTS trg_fill_system_base_model_default_snapshot ON base_model_catalog;
CREATE TRIGGER trg_fill_system_base_model_default_snapshot
BEFORE INSERT ON base_model_catalog
FOR EACH ROW
EXECUTE FUNCTION fill_system_base_model_default_snapshot();

CREATE INDEX IF NOT EXISTS idx_base_model_catalog_type
  ON base_model_catalog(catalog_type, status);
