-- pay v2 接入:订阅来源扩 'pay' + 购买台账(biz_ref↔out_trade_no 映射 + webhook 幂等消费)
ALTER TABLE subscriptions MODIFY source ENUM('trial','code','pay') NOT NULL;

CREATE TABLE pay_purchases (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id       BIGINT UNSIGNED NOT NULL,
  biz_ref       CHAR(36) NOT NULL,                -- users.uuid 冗余(webhook 兜底定位)
  sku           VARCHAR(64) NOT NULL,             -- pay products.biz_code
  out_trade_no  VARCHAR(64) NOT NULL UNIQUE,      -- pay 订单号 = 幂等键
  method        VARCHAR(32) NOT NULL,             -- alipay | crypto(retry 换渠道时更新)
  status        ENUM('created','paid','canceled') NOT NULL DEFAULT 'created',
  amount_minor  BIGINT NOT NULL DEFAULT 0,        -- webhook 回填,最小单位
  currency      VARCHAR(16) NOT NULL DEFAULT '',
  channel       VARCHAR(32) NOT NULL DEFAULT '',
  sub_id        BIGINT UNSIGNED NULL,             -- 开通/延长的 subscriptions.id
  paid_at       DATETIME(6) NULL,
  created_at    DATETIME(6) NOT NULL,
  updated_at    DATETIME(6) NOT NULL,
  INDEX idx_pay_user (user_id, created_at),
  FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
