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 - Run at midnight every day
const RUN_INTERVAL_SECONDS = 24 * 60 * 60; // 24 hours

// Calculate seconds until next midnight
function getSecondsUntilMidnight() {
  const now = new Date();
  const midnight = new Date(now);
  midnight.setHours(24, 0, 0, 0); // Next midnight
  return Math.floor((midnight - now) / 1000);
}

let remainingSeconds = getSecondsUntilMidnight();

console.log('Commission invoice scheduler started. Will generate invoices at midnight every day.');

// Function to run commission invoice generation
async function runCommissionGeneration() {
  console.log('Triggering commission invoice generation...');
  const scriptPath = path.join(__dirname, 'generate-commission-invoices.js');

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

// Countdown timer
const countdownInterval = setInterval(async () => {
  remainingSeconds -= 60; // Update every minute

  if (remainingSeconds <= 0) {
    try {
      await runCommissionGeneration();
      remainingSeconds = getSecondsUntilMidnight(); // Recalculate for next midnight
      console.log(`Next commission invoice generation in ${formatTime(remainingSeconds)}`);
    } catch (error) {
      console.error('Commission invoice generation failed, continuing countdown...');
      remainingSeconds = getSecondsUntilMidnight(); // Recalculate for next midnight
    }
  } else {
    console.log(`Next commission invoice generation in ${formatTime(remainingSeconds)}`);
  }
}, 60 * 1000); // Check every minute

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

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

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