// Finds PIS Codes using DB Lookups

const db = require("../services/dbAccess.services");
const log = require("../utils/logs.utils");
const clean = require("../utils/sanitizer.utils");

const supported = ["GW", "UK"];

async function findPisByOrigDest(start, end) {
  log.out(
    "pisServices.findPisByOrigDest: Searching for PIS for Orig: " +
      `${start}, Dest: ${end}`,
    "dbug"
  );
  const firstCrs = clean.cleanApiEndpointTxt(start.toLowerCase());
  const lastCrs = clean.cleanApiEndpointTxt(end.toLowerCase());
  const query = {
    stops: {
      $all: [
        { $elemMatch: { $eq: firstCrs } },
        { $elemMatch: { $eq: lastCrs } },
      ],
    },
    $expr: {
      $and: [
        { $eq: [{ $arrayElemAt: ["$stops", -1] }, lastCrs] },
        { $eq: [{ $arrayElemAt: ["$stops", 0] }, firstCrs] },
      ],
    },
  };
  const search = db.query("pis", query);
  return await search;
}

async function findPisByCode(code) {
  log.out(`pisServices.findPisByCode: Searching for PIS code: ${code}`, "dbug");
  const cleanCode = clean.removeNonNumeric(code);
  const query = {
    code: parseInt(cleanCode),
  };
  const search = db.query("pis", query);
  return await search;
}

async function findByTiplocArray(tiplocArray) {
  const query = {
    tiplocs: tiplocArray,
  };
  const res = db.query("pis", query);
  return await res;
}

module.exports = {
  supported,
  findPisByOrigDest,
  findPisByCode,
  findByTiplocArray,
};
