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

const router = express.Router();

router.get("/getall", async (req, res) => {
  let sql =
    "SELECT u.f_name,u.l_name,u.mail,p.name,t.time,t.date,t.user \
    FROM Timelog t \
    INNER JOIN Project p ON p.id=t.project \
    INNER JOIN User u ON u.id=t.user ";
  const where = "WHERE t.date BETWEEN ? AND ? ";
  const order = "ORDER BY ?? ";
  const offsetSql = "LIMIT 10 OFFSET ?;";
  let flag = 0;
  // construct the sql statement based on incoming request
  if (req.query.from || req.query.to) {
    sql = sql + where;
    flag += 1;
  }
  if (req.query.sortby) {
    sql = sql + order;
    flag += 2;
  }
  sql = sql + offsetSql;

  let results;
  let fields;
  switch (flag) {
    case 0:
      [results, fields] = await connection.query(sql, [
        parseInt(req.query.offset),
      ]);
      break;
    case 1:
      [results, fields] = await connection.query(sql, [
        req.query.from,
        req.query.to,
        parseInt(req.query.offset),
      ]);
      break;
    case 2:
      [results, fields] = await connection.query(sql, [
        req.query.sortby,
        parseInt(req.query.offset),
      ]);
      break;
    case 3:
      [results, fields] = await connection.query(sql, [
        req.query.from,
        req.query.to,
        req.query.sortby,
        parseInt(req.query.offset),
      ]);
      break;
  }
  res.json(results);
});

export default router;
