import axios from "axios";
import router from "@/routers";
import moment from "moment";

var options = {
  headers: {
    "Content-Type": "application/json",
    "Cache-Control": "no-cache",
    Expires: "-1",
  },
};
if (localStorage.user) {
  var curUser = JSON.parse(localStorage.user);
  console.log(curUser);
  let currentTime = moment();
  let expiredTime = moment(curUser.ExpiredTime);

  if (expiredTime.diff(currentTime, "minutes") > 1) {
    options.headers["Authorization"] = "Bearer " + curUser.Token;
  }
}
const publicClient = axios.create(options);

// Response interceptor để xử lý lỗi 401/403
publicClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      const status = error.response.status;

      if (status === 401) {
        // Unauthorized - redirect to login
        console.log("401 Unauthorized - Redirecting to login");
        router.push({ name: "login" });
      } else if (status === 403) {
        // Forbidden - redirect to unauthorized page
        console.log("403 Forbidden - Redirecting to unauthorized page");
        router.push({ name: "unauthorized" });
      }
    }

    return Promise.reject(error);
  }
);

// Giữ lại validateStatus để tương thích với code cũ
publicClient.defaults.validateStatus = function (status) {
  return status >= 200 && status < 500; // Cho phép tất cả status để interceptor xử lý
};

publicClient.LadaPath = {
  user: {
    login: "https://localhost:7284/api/Account/Login",
    listStaff: "https://id.3lada.com/api/User/SearchStaff/SearchStaff",
  },
};

export default publicClient;
