// 修复配置表不一致问题
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);

async function fixConfigIssue() {
  console.log('=== 修复飞鹅配置表不一致问题 ===\n');

  try {
    // 1. 检查当前配置状态
    console.log('1. 当前配置状态:');

    // system_config_mt 表中的飞鹅配置
    const { stdout: systemConfig } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT config_key, config_value FROM system_config_mt WHERE tenant_id = 1 AND config_key LIKE \'feie.%\' ORDER BY config_key"'
    );
    console.log('system_config_mt 表:');
    console.log(systemConfig);

    // feie_config_mt 表中的配置
    const { stdout: feieConfig } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT config_key, config_value FROM feie_config_mt WHERE tenant_id = 1 ORDER BY config_key"'
    );
    console.log('feie_config_mt 表:');
    console.log(feieConfig);

    // 2. 将 system_config_mt 中的配置复制到 feie_config_mt
    console.log('\n2. 同步配置到 feie_config_mt 表...');

    const configsToSync = [
      { key: 'feie.api.user', value: '2638601246@qq.com' },
      { key: 'feie.api.ukey', value: 'tAwVmIEv48zcIu2Y' },
      { key: 'feie.api.base_url', value: 'https://api.feieyun.cn/Api/Open/' },
      { key: 'feie.api.timeout', value: '10000' },
      { key: 'feie.api.max_retries', value: '3' },
      { key: 'feie.anti_refund_delay', value: '120' }
    ];

    for (const config of configsToSync) {
      console.log(`  同步 ${config.key} = ${config.value}`);

      // 使用 UPSERT (INSERT ... ON CONFLICT ... DO UPDATE)
      const upsertSql = `
        INSERT INTO feie_config_mt (tenant_id, config_key, config_value, created_at, updated_at)
        VALUES (1, '${config.key}', '${config.value}', NOW(), NOW())
        ON CONFLICT (tenant_id, config_key)
        DO UPDATE SET config_value = EXCLUDED.config_value, updated_at = NOW()
      `;

      await execPromise(`psql -h 127.0.0.1 -U postgres -d postgres -c "${upsertSql}"`);
    }

    // 3. 验证修复结果
    console.log('\n3. 验证修复结果...');
    const { stdout: finalConfig } = await execPromise(
      'psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT config_key, config_value FROM feie_config_mt WHERE tenant_id = 1 ORDER BY config_key"'
    );
    console.log('修复后的 feie_config_mt 表:');
    console.log(finalConfig);

    // 4. 检查必要的配置是否完整
    console.log('\n4. 检查配置完整性...');
    const requiredConfigs = [
      'feie.api.user',
      'feie.api.ukey',
      'feie.api.base_url',
      'feie.anti_refund_delay'
    ];

    const { stdout: checkResult } = await execPromise(
      `psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT config_key FROM feie_config_mt WHERE tenant_id = 1 AND config_key IN ('${requiredConfigs.join("','")}')"`
    );

    const lines = checkResult.trim().split('\n');
    const foundConfigs = lines.slice(2, -1).map(line => line.trim()); // 跳过标题行和空行

    console.log(`  找到 ${foundConfigs.length}/${requiredConfigs.length} 个必要配置:`);
    requiredConfigs.forEach(key => {
      const found = foundConfigs.includes(key);
      console.log(`  ${key}: ${found ? '✅' : '❌'}`);
    });

    if (foundConfigs.length === requiredConfigs.length) {
      console.log('\n✅ 配置修复完成！');
      console.log('\n现在可以测试支付成功触发API：');
      console.log('curl -X POST http://localhost:8080/api/v1/payments/payment/trigger-success \\');
      console.log('  -H "Content-Type: application/json" \\');
      console.log('  -H "Authorization: Bearer YOUR_TOKEN" \\');
      console.log('  -d \'{"orderId": 25}\'');
    } else {
      console.log('\n❌ 配置仍然不完整，请手动添加缺失的配置。');
    }

  } catch (error) {
    console.error('修复失败:', error.message);
  }
}

fixConfigIssue().catch(console.error);