const ldb = require("../services/ldb.services");

async function get(req, res, next) {
  // API v1 only
  try {
    var id = req.params.id;
    res.json(await ldb.get(id));
  } catch (err) {
    console.error("Unknown Error", err.message);
    err.status = 500;
    next(err);
  }
}

async function getTrain(req, res, next) {
  // API v2 Only
  if (!req.isAuthed) {
    const err = new Error("Unauthorized");
    err.status = 401;
    throw err;
  }
  let type = req.params.searchType;
  let id = req.params.id;
  try {
    switch (type.toLowerCase()) {
      case "rid":
        res.json(await ldb.getServiceByRID(id));
        break;
      case "uid":
      case "headcode":
      case "rsid":
        res.json(await ldb.getServicesByOther(id));
        break;
      default:
        res
          .status(400)
          .json({ status: "error", message: "Invalid search type" });
    }
  } catch (err) {
    err.status = 500;
    console.error("Unknown Error", err.message);
    next(err);
  }
}

async function getStation(req, res, next) {
  // API v2 Only
  let type = req.params.type;
  let id = req.params.id;
  try {
    if (type == "staff") {
      if (!req.isAuthed) {
        const err = new Error("Unauthorized");
        err.status = 401;
        return next(err);
      }
      res.json(await ldb.get(id, true));
    } else {
      res.json(await ldb.get(id, false));
    }
  } catch (err) {
    console.error("Unknown Error", err.message);
    err.status = 500;
    next(err);
  }
}

module.exports = {
  get,
  getTrain,
  getStation,
};
