const cron = require("node-cron");
const pool = require("./db");
const runCheck = require("./checkRunner");

async function scheduleChecks() {
  const { rows } = await pool.query("SELECT * FROM checks WHERE active = true");

  rows.forEach(check => {
    cron.schedule(`*/${check.schedule_seconds} * * * * *`, async () => {
      const result = await runCheck(check);

      await pool.query(
        `INSERT INTO results (check_id, status, message, duration_ms)
         VALUES ($1,$2,$3,$4)`,
        [check.id, result.status, result.message, result.duration]
      );

      await pool.query(
        `UPDATE checks SET last_run = NOW(), last_status = $1 WHERE id = $2`,
        [result.status, check.id]
      );
    });
  });
}

module.exports = scheduleChecks;
