const train = require("../services/trainService.services");

async function getByHeadcodeToday(req, res, next) {
  if (!req.isAuthed) {
    const err = new Error("Unauthorized");
    err.status = 401;
    next(err);
  }
  try {
    var searchHeadcode = req.params.id;
    res.json(await train.findByHeadcodeToday(searchHeadcode));
  } catch (err) {
    console.error("Unknown Error", err.message);
    err.status = 500;
    next(err);
  }
}

async function get(req, res, next) {
  if (!req.isAuthed) {
    const err = new Error("Unauthorized");
    err.status = 401;
    next(err);
  }
  let date = req.params.date;
  let searchType = req.params.searchType;
  let id = req.params.id;
  try {
    switch (searchType) {
      case "headcode":
        res.json(await train.findByHeadcode(date, id));
        break;
      case "byTrainUid":
        res.json(await train.findByTrainUid(id, date));
        break;
      default:
        res.status(404).json({
          status: "error",
          message: `Invalid search type "${searchType}"`,
        });
    }
  } catch (err) {
    console.error(err.message);
    err.status = 500;
    next(err);
  }
}

module.exports = {
  getByHeadcodeToday,
  get,
};
