const mongoose = require('mongoose');
const { exec } = require('child_process');
const axios = require('axios');

const MONGODB_URI = 'mongodb://10.0.0.3:27017/cms_simsswiss?replicaSet=rs0';
const TELEGRAM_TOKEN = '7780629683:AAFrbQtKtEZq-A-WZVUQgeWJXm9ilF9fNa8';
const TELEGRAM_CHAT_ID = '-4625467548';

const actionSchema = new mongoose.Schema({
  updated: Number
});
//const Action = mongoose.model('Action', actionSchema);
const Action = mongoose.model('Action', actionSchema, 'actions');


async function sendTelegramMessage(message) {
  try {
    await axios.post(`https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage`, {
      chat_id: TELEGRAM_CHAT_ID,
      text: message
    });
  } catch (err) {
    console.error('❌ Lỗi gửi Telegram:', err.message);
  }
}

async function runTask() {
  try {
    await mongoose.connect(MONGODB_URI);
    const action = await Action.findOne();

    if (action && action.updated === 1) {
      console.log('🚀 Phát hiện updated=1 → thực thi run.sh');

      exec(
        'cd /secure_site_simss_admin/www/html/sis-app-backend.simsswiss.ch/public/simsswiss.ch && bash run.sh',
        async (err, stdout, stderr) => {
          if (err) {
            console.error('❌ Lỗi chạy run.sh:', err.message);
            await sendTelegramMessage(`❌ Lỗi chạy run.sh: ${err.message}`);
            await mongoose.disconnect();
            process.exit(1);
          }

          console.log(stdout);
          console.error(stderr);

          try {
            const res = await Action.updateOne(
              { _id: action._id },
              { $set: { updated: 0 } }
            );
            console.log(`✅ Update result:`, res);
            await sendTelegramMessage('✅ Chạy run.sh thành công và đã reset updated=0');
          } catch (updateErr) {
            console.error('❌ Lỗi update:', updateErr.message);
            await sendTelegramMessage(`❌ Lỗi update: ${updateErr.message}`);
          }

          await mongoose.disconnect();
          process.exit(0);
        }
      );
    } else {
      console.log('ℹ️ Không có updated=1 → bỏ qua');
      await mongoose.disconnect();
      process.exit(0);
    }
  } catch (err) {
    console.error('❌ Lỗi:', err.message);
    await mongoose.disconnect();
    process.exit(1);
  }
}

runTask();
