-- 会员兑换码（用于无支付系统时的会员开通）

CREATE TABLE IF NOT EXISTS `membership_redeem_codes` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `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,

  `code_hash` varchar(64) NOT NULL COMMENT 'sha256(code) hex；不存明文',
  `code_suffix` varchar(16) DEFAULT NULL COMMENT '展示/审计用后缀',

  `plan` varchar(30) NOT NULL DEFAULT 'default',
  `duration_days` int NOT NULL,
  `expires_at` datetime DEFAULT NULL,

  `max_uses` int NOT NULL DEFAULT 1,
  `used_uses` int NOT NULL DEFAULT 0,
  `status` varchar(20) NOT NULL DEFAULT 'active' COMMENT 'active/disabled',

  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_redeem_code_hash` (`code_hash`),
  KEY `idx_redeem_code_suffix` (`code_suffix`),
  KEY `idx_redeem_code_deleted` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `membership_redemptions` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `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,

  `mini_program_id` bigint unsigned NOT NULL,
  `user_id` bigint unsigned NOT NULL,
  `redeem_code_id` bigint unsigned NOT NULL,
  `code_suffix` varchar(16) DEFAULT NULL,
  `membership_id` bigint unsigned NOT NULL,
  `client_ip` varchar(64) DEFAULT NULL,
  `user_agent` varchar(255) DEFAULT NULL,

  PRIMARY KEY (`id`),
  KEY `idx_redemption_user_date` (`mini_program_id`,`user_id`,`created_at`),
  KEY `idx_redemption_code` (`redeem_code_id`),
  KEY `idx_redemption_deleted` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

