-- Fami gift_tray_skin 必须绑定真实 SVGA 目录资源；旧 function/空资源行不能继续伪装成可执行视觉权益。
-- 过滤使用 idx_vip_benefit_code(app_code, benefit_code, status, level)，关联资源使用 resources 主键，
-- 只会触碰 Fami VIP5..VIP9 的小型权益矩阵，不扫描用户会员、背包或账务流水。
SET @gift_tray_contract_now_ms := CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED);

UPDATE vip_level_benefits AS benefit
LEFT JOIN resources AS resource
  ON resource.app_code = benefit.app_code
 AND resource.resource_id = benefit.resource_id
 AND resource.status = 'active'
 AND resource.resource_type = 'gift_tray_skin'
SET benefit.benefit_type = 'decoration',
    benefit.resource_type = 'gift_tray_skin',
    benefit.resource_id = CASE WHEN resource.resource_id IS NULL THEN 0 ELSE benefit.resource_id END,
    benefit.status = CASE
      WHEN resource.resource_id IS NULL
        OR TRIM(resource.animation_url) = ''
        OR LOWER(TRIM(COALESCE(JSON_UNQUOTE(JSON_EXTRACT(resource.metadata_json, '$.format')), ''))) <> 'svga'
      THEN 'disabled'
      ELSE benefit.status
    END,
    benefit.updated_at_ms = @gift_tray_contract_now_ms
WHERE benefit.app_code = 'fami'
  AND benefit.benefit_code = 'gift_tray_skin'
  AND (
    benefit.benefit_type <> 'decoration'
    OR benefit.resource_type <> 'gift_tray_skin'
    OR (benefit.resource_id > 0 AND resource.resource_id IS NULL)
    OR (
      benefit.status = 'active'
      AND (
        resource.resource_id IS NULL
        OR TRIM(resource.animation_url) = ''
        OR LOWER(TRIM(COALESCE(JSON_UNQUOTE(JSON_EXTRACT(resource.metadata_json, '$.format')), ''))) <> 'svga'
      )
    )
  );
