const jwt = require("jsonwebtoken");
const dotenv = require("dotenv");
const errorHandler = require("../util/errorHandler");
const Customers = require("../models/Customers");

dotenv.config();

module.exports = (req, res, next) => {
  const authHeader = req.get("Authorization");
  if (!authHeader) {
    req.loggedIn = false;
    return next();
  }

  const token = authHeader.split(" ")[1];
  let decodedToken;

  try {
    decodedToken = jwt.verify(token, process.env.SECRETKEY);
  } catch (err) {
    err.statusCode = 500;
    throw err;
  }

  if (!decodedToken) {
    req.loggedIn = false;
    return next();
  }

  Customers.findByPk(decodedToken.customerId)
    .then((customer) => {
      if (!customer) {
        req.loggedIn = false;
      }

      req.customerId = decodedToken.customerId;
      req.loggedIn = true;
      req.longitude = customer.longitude;
      req.latitude = customer.latitude;
      next();
    })
    .catch((err) => next(err));
};
