-- The three migrated image identities previously relied on a global
-- user-group limit. Give every upstream binding its own canonical concurrency
-- lease so raising the service group no longer removes provider protection.
WITH limits(invocation_name, policy) AS (
  VALUES
    (
      'gemini-3-pro-image',
      '{"rules":[{"metric":"concurrent","limit":10,"leaseTtlSeconds":600}]}'::jsonb
    ),
    (
      'gemini-3.1-flash-image',
      '{"rules":[{"metric":"concurrent","limit":10,"leaseTtlSeconds":600}]}'::jsonb
    ),
    (
      'gpt-image-2',
      '{"rules":[{"metric":"concurrent","limit":5,"leaseTtlSeconds":300}]}'::jsonb
    )
),
updated_base_models AS (
  UPDATE base_model_catalog base_model
  SET default_rate_limit_policy = limits.policy,
      metadata = COALESCE(base_model.metadata, '{}'::jsonb) || jsonb_build_object(
        'rateLimitSource', 'image-gateway-migration',
        'rateLimitUpdatedAt', '2026-07-24'
      ),
      updated_at = now()
  FROM limits
  WHERE base_model.invocation_name = limits.invocation_name
  RETURNING base_model.id
)
UPDATE platform_models platform_model
SET rate_limit_policy = '{}'::jsonb,
    rate_limit_policy_mode = 'inherit',
    updated_at = now()
FROM updated_base_models base_model
WHERE platform_model.base_model_id = base_model.id
  AND (
    platform_model.rate_limit_policy = '{}'::jsonb
    OR platform_model.rate_limit_policy = '{"rules":[]}'::jsonb
    OR platform_model.rate_limit_policy ? 'platformLimits'
    OR platform_model.rate_limit_policy ? 'modelLimits'
    OR platform_model.rate_limit_policy ? 'platform_limits'
    OR platform_model.rate_limit_policy ? 'model_limits'
  );
