const jwt = require("jsonwebtoken");
const dotenv = require("dotenv");
const errorHandler = require("../util/errorHandler");
const Customers = require("../models/Customers");
const SellersCompany = require("../models/SellersCompany");
const { SELLERS_SECRET_KEY } = require("../controllers/seller/accounts");

dotenv.config();

module.exports = (req, res, next) => {
  const authHeader = req.get("Authorization");
  if (!authHeader) {
    return errorHandler("Not authenticated", 401);
  }

  let isSeller = false;
  if (req.originalUrl.includes("/seller/")) {
    isSeller = true;
  }

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

  try {
    const secretKey = isSeller ? SELLERS_SECRET_KEY : process.env.SECRETKEY;
    decodedToken = jwt.verify(token, secretKey);
  } catch (err) {
    err.statusCode = 500;
    throw err;
  }

  if (!decodedToken) {
    errorHandler("Not Authenticated", 401);
  }

  if (!isSeller) {
    Customers.findOne({
      where: {
        id: decodedToken.customerId,
        account_status: true,
      },
    })
      .then((customer) => {
        if (!customer) {
          return errorHandler("User token not valid.", 401);
        }

        if (decodedToken && decodedToken.impersonation) {
          req.impersonation = true;
        }
        req.customerId = decodedToken.customerId;

        next();
      })
      .catch((err) => next(err));
  } else {
    SellersCompany.findByPk(decodedToken.seller_id)
      .then((sellerCompany) => {
        if (!sellerCompany) return errorHandler("Seller token not valid.", 401);

        req.seller_id = decodedToken.seller_id;
        req.seller_account_id = decodedToken.seller_account_id;
        req.parent_company = decodedToken.parent_company;
        next();
      })
      .catch((err) => {
        next(err);
      });
  }
};
