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

async function byOrigDest(req, res, next) {
  if (!req.isAuthed) {
    const err = new Error("Unauthorized");
    err.status = 401;
    throw err;
  }
  try {
    let start = req.params.start;
    let end = req.params.end;
    res.json(await pis.findPisByOrigDest(start, end));
  } catch (err) {
    console.error("Unknown Error", err.message);
    next(err);
  }
}

/* Used in /api/v2 */
async function byStartEndCRS(req, res, next) {
  if (!req.isAuthed) {
    const err = new Error("Unauthorized");
    err.status = 401;
    return next(err);
  }
  try {
    let startCrs = req.params.startCrs;
    let endCrs = req.params.endCrs;
    res.json(await pis.findPisByOrigDest(startCrs, endCrs));
  } catch (err) {
    console.error("Unknown Error", err.message);
    return next(err);
  }
}

/* Used in /api/v2 */
async function byCode(req, res, next) {
  if (!req.isAuthed) {
    const err = new Error("Unauthorized");
    err.status = 401;
    return next(err);
  }
  try {
    let code = req.params.code;
    res.json(await pis.findPisByCode(code));
  } catch (err) {
    console.error("Unknown Error", err.message);
    return next(err);
  }
}

async function random(req, res, next) {
  if (!req.isAuthed) {
    const err = new Error("Unauthorized");
    err.status = 401;
    return next(err);
  }
  try {
    res.json(await pis.findRandom());
  } catch (err) {
    console.error("Unknown Error", err.message);
    return next(err);
  }
}

module.exports = {
  byOrigDest,
  byStartEndCRS,
  byCode,
  random,
};
