-- 道具商店从“每个资源一个动态价格”迁移为“每个资源可有 1/3/7 天独立定价规格”。
-- 先增加带默认值的列，保证滚动发布期间旧代码仍可写入；随后把历史行回填为上线前实际展示/扣费价，
-- 因而迁移不会把既有 3/7 天商品突然降为资源列表原价。配置表数据量很小，但执行前仍应检查长事务，
-- 避免 ALTER TABLE 等待 metadata lock。
SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_wallet;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_shop_items' AND COLUMN_NAME = 'coin_price') = 0,
  'ALTER TABLE resource_shop_items ADD COLUMN coin_price BIGINT NOT NULL DEFAULT 0 COMMENT ''该售卖天数的独立金币价格；未自定义时复制资源列表价格'' AFTER duration_days',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 旧实现按 resources.coin_price * duration_days 实时计价。乘法上界保护只处理异常脏数据；正常 1/3/7
-- 天配置会完整保留迁移前价格，之后资源目录调价不再隐式影响已上架规格。
UPDATE resource_shop_items AS si
JOIN resources AS r ON r.app_code = si.app_code AND r.resource_id = si.resource_id
SET si.coin_price = CASE
  WHEN si.duration_days > 0 AND r.coin_price <= 9223372036854775807 DIV si.duration_days
    THEN r.coin_price * si.duration_days
  ELSE r.coin_price
END
WHERE si.coin_price = 0;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_shop_items' AND INDEX_NAME = 'uk_resource_shop_items_resource_duration') = 0,
  'ALTER TABLE resource_shop_items ADD UNIQUE INDEX uk_resource_shop_items_resource_duration (app_code, resource_id, duration_days)',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_shop_items' AND INDEX_NAME = 'uk_resource_shop_items_resource') > 0,
  'ALTER TABLE resource_shop_items DROP INDEX uk_resource_shop_items_resource',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
