import { api_url, version } from "../utils/consts/app.const";
import {
  handleErrorResponse,
  handleHttpError,
} from "../utils/handlers/error.handle";
import axios from "axios";

export const AuthMiddleware = async (req, res, next) => {
  try {
    if (!req.headers.authorization) {
      handleErrorResponse(res, "TOKEN_NOT_FOUND", 403);
      return;
    }

    const token = req.headers.authorization;
    const store = req.headers.store ?? '';
    axios({
      url: process.env.URL_AUTH + version + "/" + api_url + "/auth/check",
      method: "POST",
      headers: {
        store,
        Authorization: "Bearer " + token,
      },
      data: {},
    }).then((response) => {
      if (response.data.status === true) {
        req.user_id = response.data.data._id;
        next();
      } else {
        handleErrorResponse(res, "NOT_ALLOW_TOKEN_INVALID", 403);
      }
    }).catch((e) => {
      handleHttpError(res, e);
    })
  } catch (e) {
    handleHttpError(res, e);
  }
};
