const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

// Load environment variables from .env file
const envPath = path.join(__dirname, '..', '.env');
if (fs.existsSync(envPath)) {
  const envContent = fs.readFileSync(envPath, 'utf8');
  envContent.split('\n').forEach(line => {
    const [key, ...valueParts] = line.split('=');
    if (key && valueParts.length > 0) {
      const value = valueParts.join('=').trim();
      if (value.startsWith('"') && value.endsWith('"')) {
        process.env[key.trim()] = value.slice(1, -1);
      } else {
        process.env[key.trim()] = value;
      }
    }
  });
}

// Configuration
const BACKUP_INTERVAL_MINUTES = 30; // Production interval
const COUNTDOWN_INTERVAL_SECONDS = 60; // Update countdown every minute

let remainingSeconds = BACKUP_INTERVAL_MINUTES * 60;

console.log(`Backup scheduler started. Next backup in ${formatTime(remainingSeconds)}`);

// Function to format time as MM:SS
function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// Function to run backup
async function runBackup() {
  console.log('Triggering database backup...');
  const scriptPath = path.join(__dirname, 'backup.js');

  return new Promise((resolve, reject) => {
    exec(`node "${scriptPath}"`, (error, stdout, stderr) => {
      if (error) {
        console.error('Backup failed:', error);
        console.error('stderr:', stderr);
        reject(error);
      } else {
        console.log('Backup completed successfully');
        console.log(stdout);
        resolve();
      }
    });
  });
}

// Countdown timer
const countdownInterval = setInterval(async () => {
  remainingSeconds -= COUNTDOWN_INTERVAL_SECONDS;

  if (remainingSeconds <= 0) {
    try {
      await runBackup();
      remainingSeconds = BACKUP_INTERVAL_MINUTES * 60;
      console.log(`Next backup scheduled in ${formatTime(remainingSeconds)}`);
    } catch (error) {
      console.error('Backup execution failed, continuing countdown...');
      remainingSeconds = BACKUP_INTERVAL_MINUTES * 60; // Reset anyway
    }
  } else {
    console.log(`Next backup in ${formatTime(remainingSeconds)}`);
  }
}, COUNTDOWN_INTERVAL_SECONDS * 1000);

// Handle graceful shutdown
process.on('SIGINT', () => {
  console.log('Backup scheduler stopped by user');
  clearInterval(countdownInterval);
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('Backup scheduler terminated');
  clearInterval(countdownInterval);
  process.exit(0);
});