/**
 * 同步 pla_account 表的新字段
 * 添加自动投递、自动沟通、自动活跃等配置字段
 */

const Framework = require('../framework/node-core-framework.js');
const frameworkConfig = require('../config/framework.config.js');

async function syncPlaAccountFields() {
    console.log('🔄 开始同步 pla_account 表字段...\n');

    try {
        // 初始化框架
        console.log('正在初始化框架...');
        const framework = await Framework.init(frameworkConfig);
        const models = Framework.getModels();
        
        if (!models) {
            throw new Error('无法获取模型列表');
        }

        // 从任意模型获取 sequelize 实例
        const Sequelize = require('sequelize');
        const firstModel = Object.values(models)[0];
        if (!firstModel || !firstModel.sequelize) {
            throw new Error('无法获取数据库连接');
        }
        const sequelize = firstModel.sequelize;

        // 获取 pla_account 模型
        const pla_account = models.pla_account;
        if (!pla_account) {
            throw new Error('无法获取 pla_account 模型');
        }

        console.log('正在同步表结构（使用 alter: true 模式，保留现有数据）...\n');
        await pla_account.sync({ alter: true });

        console.log('✅ pla_account 表同步成功！\n');

        // 显示表结构
        const tableInfo = await sequelize.query(
            `DESCRIBE pla_account`,
            { type: Sequelize.QueryTypes.SELECT }
        );

        console.log('📋 当前表结构：');
        console.table(tableInfo.map(field => ({
            字段名: field.Field,
            类型: field.Type,
            允许空: field.Null,
            默认值: field.Default,
            注释: field.Comment || ''
        })));

        // 检查新增字段
        const newFields = [
            'auto_deliver',
            'page_count',
            'max_deliver',
            'min_salary',
            'max_salary',
            'filter_keywords',
            'exclude_keywords',
            'auto_chat',
            'chat_interval',
            'auto_reply',
            'chat_strategy',
            'auto_active',
            'active_interval',
            'active_actions'
        ];

        const existingFields = tableInfo.map(f => f.Field);

        console.log('\n🔍 检查新增字段：');
        const missingFields = [];
        newFields.forEach(field => {
            const exists = existingFields.includes(field);
            console.log(`  ${exists ? '✅' : '❌'} ${field}`);
            if (!exists) {
                missingFields.push(field);
            }
        });

        if (missingFields.length > 0) {
            console.log('\n⚠️  以下字段未添加:', missingFields.join(', '));
            console.log('建议：重新运行同步或手动添加这些字段');
        } else {
            console.log('\n✅ 所有新增字段都已存在！');
        }

        // 显示字段统计
        console.log('\n📊 字段统计：');
        console.log(`  总字段数: ${existingFields.length}`);
        console.log(`  自动投递相关: ${newFields.filter(f => ['auto_deliver', 'page_count', 'max_deliver', 'min_salary', 'max_salary', 'filter_keywords', 'exclude_keywords'].includes(f) && existingFields.includes(f)).length}/7`);
        console.log(`  自动沟通相关: ${newFields.filter(f => ['auto_chat', 'chat_interval', 'auto_reply', 'chat_strategy'].includes(f) && existingFields.includes(f)).length}/4`);
        console.log(`  自动活跃相关: ${newFields.filter(f => ['auto_active', 'active_interval', 'active_actions'].includes(f) && existingFields.includes(f)).length}/3`);

    } catch (error) {
        console.error('❌ 同步失败:', error.message);
        console.error('\n详细错误:', error);
        throw error;
    }
}

// 执行同步
syncPlaAccountFields()
    .then(() => {
        console.log('\n✨ 同步完成！');
        process.exit(0);
    })
    .catch(error => {
        console.error('\n💥 执行失败:', error);
        process.exit(1);
    });

