ALTER TABLE platform_models
  ADD COLUMN IF NOT EXISTS rate_limit_policy_mode text;

-- Historical server-main imports wrote {"rules": []} as a placeholder. It
-- means "no override", not an explicit unlimited policy.
UPDATE integration_platforms
SET rate_limit_policy = '{}'::jsonb,
    updated_at = now()
WHERE rate_limit_policy = '{"rules":[]}'::jsonb;

UPDATE platform_models
SET rate_limit_policy = '{}'::jsonb,
    updated_at = now()
WHERE rate_limit_policy = '{"rules":[]}'::jsonb;

UPDATE platform_models model
SET runtime_policy_set_id = NULL,
    runtime_policy_override = '{}'::jsonb
FROM base_model_catalog base
WHERE model.base_model_id = base.id
  AND model.runtime_policy_set_id IS NOT DISTINCT FROM base.runtime_policy_set_id
  AND model.runtime_policy_override IS NOT DISTINCT FROM base.runtime_policy_override;

UPDATE platform_models model
SET rate_limit_policy_mode = CASE
  WHEN model.runtime_policy_override ? 'rateLimitPolicy' THEN 'override'
  WHEN model.rate_limit_policy <> '{}'::jsonb
    AND (
      base.id IS NULL
      OR model.rate_limit_policy IS DISTINCT FROM base.default_rate_limit_policy
    )
    THEN 'override'
  ELSE 'inherit'
END
FROM (
  SELECT platform_model.id AS platform_model_id, catalog.id, catalog.default_rate_limit_policy
  FROM platform_models platform_model
  LEFT JOIN base_model_catalog catalog ON catalog.id = platform_model.base_model_id
) base
WHERE model.id = base.platform_model_id
  AND model.rate_limit_policy_mode IS NULL;

UPDATE platform_models
SET rate_limit_policy_mode = 'inherit'
WHERE rate_limit_policy_mode IS NULL;

ALTER TABLE platform_models
  ALTER COLUMN rate_limit_policy_mode SET DEFAULT 'inherit';

ALTER TABLE platform_models
  ADD CONSTRAINT platform_models_rate_limit_policy_mode_check
  CHECK (
    COALESCE(rate_limit_policy_mode, '') IN ('inherit', 'override')
  )
  NOT VALID;

ALTER TABLE platform_models
  VALIDATE CONSTRAINT platform_models_rate_limit_policy_mode_check;
