const fs = require('fs');
const initSqlJs = require('sql.js');

initSqlJs().then(SQL => {
    const dbPath = 'data/worktime.db';
    const fileBuffer = fs.readFileSync(dbPath);
    const db = new SQL.Database(fileBuffer);

    // 预览一下会受影响的记录
    const preview = db.exec(`
        SELECT id, user_id, work_date, hours, project_type
        FROM timesheets
        WHERE project_type = 'M510--DSA'
        ORDER BY work_date
    `);
    if (preview.length > 0) {
        console.log('=== 将被更正的记录 ===');
        preview[0].values.forEach(row => console.log(row.join(' | ')));
    }

    // 执行合并：把 M510--DSA 统一改为 M510-DSA
    db.run(`UPDATE timesheets SET project_type = 'M510-DSA' WHERE project_type = 'M510--DSA'`);

    // 同时修正 project_types 预设表里的错误项（如果有）
    const ptCheck = db.exec(`SELECT id, name FROM project_types WHERE name = 'M510--DSA'`);
    if (ptCheck.length > 0 && ptCheck[0].values.length > 0) {
        // 先检查 M510-DSA 是否已存在于预设表
        const correctExists = db.exec(`SELECT id FROM project_types WHERE name = 'M510-DSA'`);
        if (correctExists.length > 0 && correctExists[0].values.length > 0) {
            // 正确项已存在，直接删除错误项
            db.run(`DELETE FROM project_types WHERE name = 'M510--DSA'`);
            console.log('\n已从子项目预设表中删除重复项 "M510--DSA"');
        } else {
            // 正确项不存在，把错误项改名
            db.run(`UPDATE project_types SET name = 'M510-DSA' WHERE name = 'M510--DSA'`);
            console.log('\n已在子项目预设表中将 "M510--DSA" 更名为 "M510-DSA"');
        }
    }

    // 验证结果
    const verify = db.exec(`
        SELECT project_type, COUNT(*) as cnt, SUM(hours) as total_hours
        FROM timesheets
        WHERE project_type IN ('M510-DSA', 'M510--DSA')
        GROUP BY project_type
    `);
    console.log('\n=== 合并结果验证 ===');
    if (verify.length > 0) {
        console.log(verify[0].columns.join(' | '));
        verify[0].values.forEach(row => console.log(row.join(' | ')));
    } else {
        console.log('无 M510--DSA 记录（已全部合并）');
    }

    // 保存写回磁盘
    const data = db.export();
    fs.writeFileSync(dbPath, data);
    console.log('\n✅ 数据库已保存，合并完成！');
});
