import express from "express";
import connection from "../db.js";

const router = express.Router();

router.get("/gettopten", async (req, res) => {
  let from = "2020-01-01";
  let to = "2029-01-01";
  let filterBy = "user";
  if (req.query.from) from = req.query.from;
  if (req.query.to) to = req.query.to;
  if (req.query.filterBy) filterBy = req.query.filterBy;
  let results, fields;
  let filterBySql = filterBy === "user" ? "t.user" : "t.project";
  try {
    [results, fields] = await connection.query(
      "SELECT t.user,t.date,t.project,u.f_name,u.l_name,p.name,SUM(t.time) as total_time \
    FROM Timelog t \
    INNER JOIN Project p ON p.id=t.project \
    INNER JOIN User u ON u.id=t.user \
    WHERE t.date BETWEEN ? AND ? \
    GROUP BY ?? \
    ORDER BY total_time DESC\
    LIMIT 10;",
      [from, to, filterBySql],
    );
  } catch (err) {
    console.log(err);
    res.status(400).json({ message: "Error" });
  }

  res.json(results);
});

export default router;
