CREATE TABLE IF NOT EXISTS `promo_rule` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称',
  `type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '规则类型：new_user / inactive_user / campaign',
  `params` JSON NOT NULL COMMENT '类型专属参数',
  `priority` INT NOT NULL DEFAULT 0 COMMENT '优先级，数值越大越优先匹配',
  `enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
  `start_time` DATETIME DEFAULT NULL COMMENT '生效开始时间',
  `end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
  PRIMARY KEY (`id`),
  KEY `idx_enabled_priority` (`enabled`, `priority` DESC),
  KEY `idx_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';

CREATE TABLE IF NOT EXISTS `subscribe_promo` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
  `quantity` INT NOT NULL DEFAULT 0 COMMENT '购买数量',
  `promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
  `promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '优惠价（分）',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_subscribe_qty_rule` (`subscribe_id`, `quantity`, `promo_rule_id`),
  KEY `idx_promo_rule_id` (`promo_rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';

CREATE TABLE IF NOT EXISTS `promo_usage` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
  `promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
  `subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
  `order_no` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '关联订单号',
  `promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '使用时的促销单价（分）',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_user_rule` (`user_id`, `promo_rule_id`),
  KEY `idx_order_no` (`order_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
