-- 迁移脚本：为缺少 user_id 的表添加该列
-- 适用于旧版数据库升级

-- transactions 表添加 user_id
ALTER TABLE transactions ADD COLUMN user_id INT NOT NULL DEFAULT 1 AFTER id;
ALTER TABLE transactions ADD INDEX idx_user_date (user_id, date);
ALTER TABLE transactions ADD INDEX idx_user_type_date (user_id, type, date);
ALTER TABLE transactions ADD FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;

-- budgets 表添加 user_id
ALTER TABLE budgets ADD COLUMN user_id INT NOT NULL DEFAULT 1 AFTER id;
ALTER TABLE budgets ADD UNIQUE KEY uk_user_month (user_id, month);
ALTER TABLE budgets ADD FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;

-- categories 表确认 user_id 存在（旧版可能也没有）
ALTER TABLE categories ADD COLUMN IF NOT EXISTS user_id INT DEFAULT 0 COMMENT '0=默认分类, 其他=用户自定义' AFTER id;

-- v2 迭代迁移

-- users 表：新增软删除字段
ALTER TABLE users ADD COLUMN IF NOT EXISTS deleted_at DATETIME DEFAULT NULL COMMENT '软删除时间（NULL=正常）';
CREATE INDEX IF NOT EXISTS idx_users_deleted ON users(deleted_at);

-- 新增 refresh_tokens 表
CREATE TABLE IF NOT EXISTS refresh_tokens (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  token_hash VARCHAR(64) NOT NULL COMMENT 'SHA-256(token)',
  expires_at DATETIME NOT NULL COMMENT '过期时间',
  revoked_at DATETIME DEFAULT NULL COMMENT '撤销时间（NULL=有效）',
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_user (user_id),
  INDEX idx_hash (token_hash),
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
