-- 激活码
CREATE TABLE code_batches (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  channel     TEXT NOT NULL CHECK (channel IN ('store','tg','line','manual')),
  created_by  TEXT NOT NULL,
  note        TEXT NULL,
  created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE codes (
  id            INTEGER PRIMARY KEY AUTOINCREMENT,
  code_hash     TEXT NOT NULL UNIQUE,              -- SHA-256
  plan_id       INTEGER NOT NULL,
  duration_days INTEGER NOT NULL,
  batch_id      INTEGER NOT NULL,
  status        TEXT NOT NULL DEFAULT 'unused' CHECK (status IN ('unused','redeemed','void')),
  redeemed_by   INTEGER NULL,
  redeemed_at   DATETIME NULL,
  FOREIGN KEY (plan_id) REFERENCES plans(id),
  FOREIGN KEY (batch_id) REFERENCES code_batches(id)
);
CREATE INDEX idx_codes_status ON codes (status);
