const { createApp } = require('./app');
const { runAlertCycle } = require('./services/alerts');
const { runScheduledSync } = require('./services/workday');
const { runScheduledRecompute } = require('./services/pm');

const PORT = Number(process.env.PORT || process.env.DEPRECORE_PORT || 3000);
const app = createApp();

app.listen(PORT, () => {
  console.log(`DepreCore API listening on http://localhost:${PORT}`);
});

// Periodically scan for due/expiring items and email digests. These are no-ops
// unless alerts are enabled and SMTP is configured. Runs after boot, then twice daily.
function scheduleAlertCycle() {
  const tick = () => runAlertCycle(null).catch((error) => console.error('Alert cycle failed:', error.message));
  setTimeout(tick, 30_000).unref();
  setInterval(tick, 12 * 60 * 60 * 1000).unref();
}

// Hourly check for a due automatic Workday sync (respects the configured interval).
function scheduleWorkdaySync() {
  const tick = () => runScheduledSync().catch((error) => console.error('Workday sync failed:', error.message));
  setTimeout(tick, 60_000).unref();
  setInterval(tick, 60 * 60 * 1000).unref();
}

// Hourly tick that lets the PM recompute job self-gate to its configured nightly hour. Keeps dynamic
// (usage/lifespan) due-dates fresh for schedules that aren't completed or read between runs.
function schedulePmRecompute() {
  const tick = () => {
    try {
      runScheduledRecompute();
    } catch (error) {
      console.error('PM recompute failed:', error.message);
    }
  };
  setTimeout(tick, 90_000).unref();
  setInterval(tick, 60 * 60 * 1000).unref();
}

scheduleAlertCycle();
scheduleWorkdaySync();
schedulePmRecompute();
