-- 迁移文件: 032_create_voice_clone_v2_table.sql
-- 描述: 创建声音克隆任务表V2（异步模式）
-- 策略: 创建新表，不影响现有 voice_clone 表

-- ============================================
-- 正向迁移: 创建表和索引
-- ============================================

-- 创建 voice_clone_v2 表
CREATE TABLE IF NOT EXISTS voice_clone_v2 (
    id SERIAL PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL,
    task_id VARCHAR(100) NOT NULL UNIQUE,
    voice_id VARCHAR(200),
    target_model VARCHAR(100) NOT NULL,
    prefix VARCHAR(20) NOT NULL,
    voice_name VARCHAR(50),
    audio_url VARCHAR(500),
    status VARCHAR(20) DEFAULT 'PENDING',
    bill NUMERIC(10, 4) DEFAULT 0,
    error_message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMP,
    CONSTRAINT fk_voice_clone_v2_user 
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- 添加表注释
COMMENT ON TABLE voice_clone_v2 IS '声音克隆任务表V2（异步模式，统一架构）';
COMMENT ON COLUMN voice_clone_v2.id IS '主键ID';
COMMENT ON COLUMN voice_clone_v2.user_id IS '用户ID（外键关联users表）';
COMMENT ON COLUMN voice_clone_v2.task_id IS 'DashScope任务ID（唯一）';
COMMENT ON COLUMN voice_clone_v2.voice_id IS '生成的音色ID（完成后）';
COMMENT ON COLUMN voice_clone_v2.target_model IS '目标TTS模型';
COMMENT ON COLUMN voice_clone_v2.prefix IS '音色前缀名称';
COMMENT ON COLUMN voice_clone_v2.voice_name IS '音色名称（用户输入）';
COMMENT ON COLUMN voice_clone_v2.audio_url IS '原始音频文件OSS地址';
COMMENT ON COLUMN voice_clone_v2.status IS '任务状态（PENDING/PROCESSING/SUCCEEDED/FAILED）';
COMMENT ON COLUMN voice_clone_v2.bill IS '费用（元）';
COMMENT ON COLUMN voice_clone_v2.error_message IS '错误信息（失败时）';
COMMENT ON COLUMN voice_clone_v2.created_at IS '创建时间';
COMMENT ON COLUMN voice_clone_v2.updated_at IS '更新时间';
COMMENT ON COLUMN voice_clone_v2.completed_at IS '完成时间';

-- 创建索引（优化查询性能）
CREATE INDEX idx_voice_clone_v2_user_id ON voice_clone_v2(user_id);
CREATE INDEX idx_voice_clone_v2_task_id ON voice_clone_v2(task_id);
CREATE INDEX idx_voice_clone_v2_voice_id ON voice_clone_v2(voice_id);
CREATE INDEX idx_voice_clone_v2_status ON voice_clone_v2(status);
CREATE INDEX idx_voice_clone_v2_created_at ON voice_clone_v2(created_at DESC);

-- ============================================
-- 回滚迁移: 删除表和索引
-- ============================================
-- DROP INDEX IF EXISTS idx_voice_clone_v2_created_at;
-- DROP INDEX IF EXISTS idx_voice_clone_v2_status;
-- DROP INDEX IF EXISTS idx_voice_clone_v2_voice_id;
-- DROP INDEX IF EXISTS idx_voice_clone_v2_task_id;
-- DROP INDEX IF EXISTS idx_voice_clone_v2_user_id;
-- DROP TABLE IF EXISTS voice_clone_v2;
