-- M-MEMBER-01-02: Expand 账号令牌、商品映射、会员 Grant 与 PlanQuota Schema
-- Expand only — 不删除旧字段、不破坏 Admin 手动会员

-- 1. User.appAccountToken
ALTER TABLE `User`
  ADD COLUMN `appAccountToken` CHAR(36) NULL,
  ADD UNIQUE INDEX `User_appAccountToken_key` (`appAccountToken`);

-- 2. MembershipPlan.monthlyQuizCount
ALTER TABLE `MembershipPlan`
  ADD COLUMN `monthlyQuizCount` INT NOT NULL DEFAULT 0;

-- 3. StoreProduct（新增）
CREATE TABLE `StoreProduct` (
  `id` VARCHAR(191) NOT NULL,
  `platform` VARCHAR(16) NOT NULL,
  `productId` VARCHAR(100) NOT NULL,
  `planId` VARCHAR(191) NOT NULL,
  `billingPeriod` VARCHAR(16) NOT NULL,
  `isActive` BOOLEAN NOT NULL DEFAULT true,
  `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updatedAt` DATETIME(3) NOT NULL,

  PRIMARY KEY (`id`),
  UNIQUE INDEX `StoreProduct_platform_productId_key` (`platform`, `productId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 4. UserMembership 扩展
ALTER TABLE `UserMembership`
  ADD COLUMN `source` VARCHAR(32) NOT NULL DEFAULT 'admin',
  ADD COLUMN `status` VARCHAR(32) NOT NULL DEFAULT 'active',
  ADD COLUMN `productId` VARCHAR(100) NULL,
  ADD COLUMN `originalTransactionId` VARCHAR(255) NULL,
  ADD COLUMN `transactionId` VARCHAR(255) NULL,
  ADD COLUMN `environment` VARCHAR(16) NULL,
  ADD COLUMN `purchaseDate` DATETIME(3) NULL,
  ADD COLUMN `expiresDate` DATETIME(3) NULL,
  ADD COLUMN `gracePeriodExpiresAt` DATETIME(3) NULL,
  ADD COLUMN `autoRenewStatus` VARCHAR(32) NULL,
  ADD COLUMN `revocationDate` DATETIME(3) NULL,
  ADD COLUMN `revocationReason` VARCHAR(64) NULL,
  ADD COLUMN `ownershipType` VARCHAR(32) NULL,
  ADD COLUMN `appAccountToken` VARCHAR(255) NULL,
  ADD COLUMN `serverNotificationId` VARCHAR(191) NULL,
  ADD UNIQUE INDEX `UserMembership_originalTransactionId_key` (`originalTransactionId`),
  ADD UNIQUE INDEX `UserMembership_transactionId_key` (`transactionId`),
  ADD INDEX `UserMembership_expiresDate_idx` (`expiresDate`),
  ADD INDEX `UserMembership_source_idx` (`source`),
  ADD INDEX `UserMembership_status_idx` (`status`);

-- 5. PlanQuota（新增）
CREATE TABLE `PlanQuota` (
  `id` VARCHAR(191) NOT NULL,
  `planId` VARCHAR(191) NOT NULL,
  `quotaType` VARCHAR(64) NOT NULL,
  `limit` INT NOT NULL DEFAULT 0,
  `unit` VARCHAR(32) NOT NULL,
  `windowType` VARCHAR(32) NOT NULL,
  `isUnlimited` BOOLEAN NOT NULL DEFAULT false,
  `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updatedAt` DATETIME(3) NOT NULL,

  PRIMARY KEY (`id`),
  UNIQUE INDEX `PlanQuota_planId_quotaType_key` (`planId`, `quotaType`),
  INDEX `PlanQuota_quotaType_idx` (`quotaType`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 6. 回填说明（不在此 Migration 中执行）
-- appAccountToken 回填：
--   1. 分批 UPDATE User SET appAccountToken = UUID() WHERE appAccountToken IS NULL
--   2. 确认无重复后执行 ALTER TABLE User MODIFY COLUMN appAccountToken CHAR(36) NOT NULL
--   3. 回填脚本另行提供，不在 Schema Migration 中执行
