const client = require("../graphql-client/graphql-client").client;
const queries = require("../graphql-client/queries");
const logger = require("../utils/logger");

exports.techLogin = async (req, res) => {
  const { shopid, employeeid, pin } = req.body;
  logger.log("tech-console-login", "DEBUG", req.user.email, null, null);
  try {
    const result = await client.request(queries.QUERY_EMPLOYEE_PIN, {
      shopId: shopid,
      employeeId: employeeid
    });

    let valid = false;
    let error;
    let technician;
    if (result.employees && result.employees[0]) {
      const dbRecord = result.employees[0];
      if (dbRecord.pin === pin && dbRecord.active === true) {
        valid = true;
        delete dbRecord.pin;
        technician = dbRecord;
      } else {
        logger.log("tech-console-login-error", "DEBUG", req.user.email, null, {
          type: "wrong-pin"
        });

        error = "The employee ID and PIN combination are not correct.";
      }
    } else {
      logger.log("tech-console-login-error", "DEBUG", req.user.email, null, {
        type: "invalid-employee"
      });
      error = "The employee ID does not exist.";
    }
    res.json({ valid, technician, error });
  } catch (error) {
    logger.log("tech-console-login-error", "DEBUG", req.user.email, null, {
      error
    });
    res.status(400).send(error);
  }
};
