-- M-MEMBER-01-03: 不可变 App Store 交易、通知 Inbox 与 Payload 审计模型

-- 1. AppStoreTransaction（不可变交易记录）
CREATE TABLE `AppStoreTransaction` (
  `id` VARCHAR(191) NOT NULL,
  `userId` VARCHAR(191) NOT NULL,
  `membershipId` VARCHAR(191) NULL,
  `productId` VARCHAR(100) NOT NULL,
  `transactionId` VARCHAR(255) NOT NULL,
  `originalTransactionId` VARCHAR(255) NOT NULL,
  `appAccountToken` VARCHAR(255) NOT NULL,
  `environment` VARCHAR(16) NOT NULL,
  `purchaseDate` DATETIME(3) NOT NULL,
  `originalPurchaseDate` DATETIME(3) NOT NULL,
  `expiresDate` DATETIME(3) NULL,
  `revocationDate` DATETIME(3) NULL,
  `revocationReason` VARCHAR(64) NULL,
  `ownershipType` VARCHAR(32) NULL,
  `signedDate` DATETIME(3) NOT NULL,
  `transactionReason` VARCHAR(64) NULL,
  `webOrderLineItemId` VARCHAR(255) NULL,
  `rawPayloadHash` CHAR(64) NOT NULL,
  `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

  PRIMARY KEY (`id`),
  UNIQUE INDEX `AppStoreTransaction_transactionId_key` (`transactionId`),
  INDEX `AppStoreTransaction_originalTransactionId_idx` (`originalTransactionId`),
  INDEX `AppStoreTransaction_userId_idx` (`userId`),
  INDEX `AppStoreTransaction_productId_idx` (`productId`),
  INDEX `AppStoreTransaction_expiresDate_idx` (`expiresDate`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 2. AppStoreNotification（Durable Inbox）
CREATE TABLE `AppStoreNotification` (
  `id` VARCHAR(191) NOT NULL,
  `notificationUuid` VARCHAR(255) NOT NULL,
  `notificationType` VARCHAR(64) NOT NULL,
  `subtype` VARCHAR(64) NULL,
  `environment` VARCHAR(16) NOT NULL,
  `signedDate` DATETIME(3) NOT NULL,
  `originalTransactionId` VARCHAR(255) NULL,
  `transactionId` VARCHAR(255) NULL,
  `userId` VARCHAR(191) NULL,
  `processedStatus` VARCHAR(32) NOT NULL DEFAULT 'received',
  `processingStartedAt` DATETIME(3) NULL,
  `processedAt` DATETIME(3) NULL,
  `retryCount` INT NOT NULL DEFAULT 0,
  `nextRetryAt` DATETIME(3) NULL,
  `errorCode` VARCHAR(64) NULL,
  `errorMessage` VARCHAR(1000) NULL,
  `payloadHash` CHAR(64) NOT NULL,
  `payloadObjectKey` VARCHAR(500) NULL,
  `payloadExpiresAt` DATETIME(3) NULL,
  `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

  PRIMARY KEY (`id`),
  UNIQUE INDEX `AppStoreNotification_notificationUuid_key` (`notificationUuid`),
  INDEX `AppStoreNotification_originalTransactionId_idx` (`originalTransactionId`),
  INDEX `AppStoreNotification_notificationType_idx` (`notificationType`),
  INDEX `AppStoreNotification_processedStatus_idx` (`processedStatus`),
  INDEX `AppStoreNotification_createdAt_idx` (`createdAt`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
