-- 修复template_materials表的file_size字段，允许为NULL
-- 重建表以修改字段约束

CREATE TABLE template_materials_new (
    id TEXT PRIMARY KEY,
    template_id TEXT NOT NULL,
    original_id TEXT NOT NULL,
    name TEXT NOT NULL,
    material_type TEXT NOT NULL,
    original_path TEXT NOT NULL,
    remote_url TEXT,
    file_size INTEGER,  -- 移除NOT NULL约束
    duration INTEGER,
    width INTEGER,
    height INTEGER,
    upload_status TEXT NOT NULL DEFAULT 'Pending',
    file_exists BOOLEAN DEFAULT FALSE,
    upload_success BOOLEAN DEFAULT FALSE,
    metadata TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (template_id) REFERENCES templates (id) ON DELETE CASCADE
);

-- 迁移现有数据
INSERT INTO template_materials_new 
SELECT id, template_id, original_id, name, material_type, original_path,
       remote_url, file_size, duration, width, height, upload_status,
       file_exists, upload_success, metadata, created_at, updated_at
FROM template_materials;

-- 删除旧表并重命名新表
DROP TABLE template_materials;
ALTER TABLE template_materials_new RENAME TO template_materials;

-- 重新创建索引
CREATE INDEX IF NOT EXISTS idx_template_materials_template_id ON template_materials (template_id);
CREATE INDEX IF NOT EXISTS idx_template_materials_upload_status ON template_materials (upload_status);
CREATE INDEX IF NOT EXISTS idx_template_materials_original_id ON template_materials (original_id);
