-- 订阅 source 扩 'pay':重建表(CHECK 约束不可 ALTER)
CREATE TABLE subscriptions_new (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id     INTEGER NOT NULL,
  plan_id     INTEGER NOT NULL,
  expires_at  DATETIME NOT NULL,
  source      TEXT NOT NULL CHECK (source IN ('trial','code','pay')),
  created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id),
  FOREIGN KEY (plan_id) REFERENCES plans(id)
);
INSERT INTO subscriptions_new (id, user_id, plan_id, expires_at, source, created_at)
  SELECT id, user_id, plan_id, expires_at, source, created_at FROM subscriptions;
DROP TABLE subscriptions;
ALTER TABLE subscriptions_new RENAME TO subscriptions;
CREATE INDEX idx_subs_user_exp ON subscriptions (user_id, expires_at);

CREATE TABLE pay_purchases (
  id            INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id       INTEGER NOT NULL,
  biz_ref       TEXT NOT NULL,
  sku           TEXT NOT NULL,
  out_trade_no  TEXT NOT NULL UNIQUE,
  method        TEXT NOT NULL,
  status        TEXT NOT NULL DEFAULT 'created' CHECK (status IN ('created','paid','canceled')),
  amount_minor  INTEGER NOT NULL DEFAULT 0,
  currency      TEXT NOT NULL DEFAULT '',
  channel       TEXT NOT NULL DEFAULT '',
  sub_id        INTEGER NULL,
  paid_at       DATETIME NULL,
  created_at    DATETIME NOT NULL,
  updated_at    DATETIME NOT NULL,
  FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE INDEX idx_pay_user ON pay_purchases (user_id, created_at);
