const express = require("express");
const pool = require("./db");
const scheduleChecks = require("./scheduler");

const runCheck = require("./checkRunner");

const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));

app.get("/", async (req, res) => {
  const { rows } = await pool.query("SELECT * FROM checks ORDER BY id");
  res.render("index", { checks: rows });
});

app.post("/run/:id", async (req, res) => {
  const checkId = req.params.id;

  const { rows } = await pool.query("SELECT * FROM checks WHERE id = $1", [checkId]);
  if (rows.length === 0) {
    return res.status(404).send("Check not found");
  }

  const check = rows[0];
  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]
  );

  res.redirect("/");
});


app.listen(3000, async () => {
  console.log("Server läuft auf Port 3000");
  await scheduleChecks();
});
