-- ============================================================
-- LiteMall v1.4.2 老库升级脚本（砍价模块安全加固）
-- 适用：已安装 v1.4.1（含砍价模块）的库
-- 内容：bargain_sessions 加 CHECK 约束 + 覆盖索引（与生产、基座 init-db 一致）
-- 说明：SQLite 无法 ALTER 加 CHECK，需重建表（数据无损迁移）
-- ============================================================

BEGIN;

-- 1) 重建 bargain_sessions 加 CHECK（非负 + current>=floor），数据无损
CREATE TABLE IF NOT EXISTS bargain_sessions_new (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  session_no TEXT UNIQUE,
  activity_id INTEGER,
  user_id INTEGER,
  original_price REAL,
  current_price REAL,
  floor_price REAL,
  quantity INTEGER,
  helped_count INTEGER,
  status TEXT,
  expire_at DATETIME,
  created_at DATETIME,
  CHECK(current_price>=0 AND floor_price>=0 AND current_price>=floor_price)
);

INSERT INTO bargain_sessions_new(session_no,activity_id,user_id,original_price,current_price,floor_price,quantity,helped_count,status,expire_at,created_at)
  SELECT session_no,activity_id,user_id,original_price,current_price,floor_price,quantity,helped_count,status,expire_at,created_at
  FROM bargain_sessions;

DROP TABLE bargain_sessions;
ALTER TABLE bargain_sessions_new RENAME TO bargain_sessions;

-- 2) 覆盖索引
CREATE INDEX IF NOT EXISTS idx_bs_activity_user_status ON bargain_sessions(activity_id, user_id, status);
CREATE INDEX IF NOT EXISTS idx_ba_status ON bargain_activities(status, id);
CREATE INDEX IF NOT EXISTS idx_bh_session_activity_user ON bargain_helps(session_id, activity_id, user_id);

COMMIT;

-- 校验（应输出 current_price>=0 且 current_price>=floor_price 的约束）
-- SELECT sql FROM sqlite_master WHERE type='table' AND name='bargain_sessions';
