-- 短信验证码功能数据库迁移脚本
-- 执行方式: psql -U postgres -d life_echo -f migrations/add_sms_verification.sql

-- 1. 创建短信验证码表
CREATE TABLE IF NOT EXISTS sms_verification_codes (
    id VARCHAR PRIMARY KEY,
    phone VARCHAR NOT NULL,
    code VARCHAR NOT NULL,
    purpose VARCHAR NOT NULL,
    is_used BOOLEAN DEFAULT FALSE,
    is_expired BOOLEAN DEFAULT FALSE,
    expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    verified_at TIMESTAMP WITH TIME ZONE,
    ip_address VARCHAR
);

-- 2. 创建索引以提高查询性能
CREATE INDEX IF NOT EXISTS idx_sms_phone ON sms_verification_codes(phone);
CREATE INDEX IF NOT EXISTS idx_sms_created_at ON sms_verification_codes(created_at);
CREATE INDEX IF NOT EXISTS idx_sms_purpose ON sms_verification_codes(purpose);
CREATE INDEX IF NOT EXISTS idx_sms_phone_purpose ON sms_verification_codes(phone, purpose);

-- 3. 扩展 refresh_tokens 表，添加设备信息字段
ALTER TABLE refresh_tokens ADD COLUMN IF NOT EXISTS device_info VARCHAR;

-- 4. 添加注释
COMMENT ON TABLE sms_verification_codes IS '短信验证码表';
COMMENT ON COLUMN sms_verification_codes.id IS '主键ID';
COMMENT ON COLUMN sms_verification_codes.phone IS '手机号';
COMMENT ON COLUMN sms_verification_codes.code IS '6位验证码';
COMMENT ON COLUMN sms_verification_codes.purpose IS '用途：register/login/reset_password/change_phone';
COMMENT ON COLUMN sms_verification_codes.is_used IS '是否已使用';
COMMENT ON COLUMN sms_verification_codes.is_expired IS '是否已过期';
COMMENT ON COLUMN sms_verification_codes.expires_at IS '过期时间（5分钟后）';
COMMENT ON COLUMN sms_verification_codes.created_at IS '创建时间';
COMMENT ON COLUMN sms_verification_codes.verified_at IS '验证时间';
COMMENT ON COLUMN sms_verification_codes.ip_address IS '请求IP地址';

COMMENT ON COLUMN refresh_tokens.device_info IS '设备信息（用于全设备登出）';

-- 5. 显示迁移完成信息
DO $$
BEGIN
    RAISE NOTICE '短信验证码功能迁移完成！';
    RAISE NOTICE '- 已创建 sms_verification_codes 表';
    RAISE NOTICE '- 已创建相关索引';
    RAISE NOTICE '- 已扩展 refresh_tokens 表';
END $$;
