-- mini_programs 表存储小程序凭证
CREATE TABLE IF NOT EXISTS `mini_programs` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `created_at` datetime(3) NULL DEFAULT NULL,
  `updated_at` datetime(3) NULL DEFAULT NULL,
  `deleted_at` datetime(3) NULL DEFAULT NULL,
  `name` varchar(100) NOT NULL,
  `app_id` varchar(100) NOT NULL,
  `app_secret` varchar(200) NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_mini_programs_app_id` (`app_id`),
  KEY `idx_mini_programs_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- users 表结构，与 internal/model/user.go 对应
CREATE TABLE IF NOT EXISTS `users` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `created_at` datetime(3) NULL DEFAULT NULL,
  `updated_at` datetime(3) NULL DEFAULT NULL,
  `deleted_at` datetime(3) NULL DEFAULT NULL,
  `mini_program_id` bigint unsigned NOT NULL,
  `open_id` varchar(100) NOT NULL,
  `union_id` varchar(100) DEFAULT NULL,
  `nick_name` varchar(100) DEFAULT NULL,
  `avatar_url` varchar(500) DEFAULT NULL,
  `gender` tinyint(1) NOT NULL DEFAULT 0,
  `phone` varchar(20) DEFAULT NULL,
  `session_key` varchar(100) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_mini_open` (`mini_program_id`,`open_id`),
  KEY `idx_users_deleted_at` (`deleted_at`),
  CONSTRAINT `fk_users_mini_program` FOREIGN KEY (`mini_program_id`) REFERENCES `mini_programs`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 会员订阅（通用能力：可给多个功能做“会员优先/免广告”策略）
-- 说明：
-- - 会员判断：存在 `status='active' AND ends_at > NOW()` 的记录即可视为会员
-- - 如果你不想引入该表，也可以选择在 users 表新增 `vip_expires_at` 字段（但扩展性较弱）
CREATE TABLE IF NOT EXISTS `user_memberships` (
  `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,
  `plan` varchar(30) NOT NULL COMMENT '例如：month/year/lifetime',
  `status` varchar(20) NOT NULL COMMENT 'active/canceled/expired',
  `starts_at` datetime NOT NULL,
  `ends_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_membership_user` (`mini_program_id`,`user_id`,`ends_at`),
  KEY `idx_membership_status` (`mini_program_id`,`user_id`,`status`,`ends_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
