"use client";
import axios from "axios";
import Cookies from "js-cookie";
import qs from "qs";

const baseURL = "https://netidhub.com/api/";
const tokenAuth = Cookies.get("access_token")
  ? Cookies.get("access_token")
  : null;
const expired = Cookies.get("time_refresh")
  ? Cookies.get("time_refresh")
  : null;

const axiosInterceptor = axios.create({
  baseURL,
  headers: {
    Authorization: `Bearer ${tokenAuth}`,
  },
});

axiosInterceptor.interceptors.request.use(async (req) => {
  const time = new Date();
  const expiredValue = Cookies.get("time_refresh"); // Assuming 'time_refresh' contains `expired`

  if (expiredValue) {
    const expired = new Date(expiredValue); // Ensure valid Date object
    if (time.getTime() >= expired.getTime()) {
      const url = `${baseURL}/signin`;
      const data = {
        grant_type: "refresh_token",
        client_id: "mediahub-app",
        refresh_token: Cookies.get("refresh_token") || "", // Fallback to empty string if undefined
      };

      const response = await axios
        .post(url, qs.stringify(data))
        .catch((error) => error.response);

      if (response?.status === 401) {
        Object.keys(Cookies.get() || {}).forEach((cookieName) => {
          Cookies.remove(cookieName);
        });
        window.location.href = "/";
      } else {
        const { access_token, refresh_token } = response?.data || {};
        const dateTime = new Date();
        const newTime = dateTime.getTime() + 10 * 60 * 1000;
        Cookies.set("access_token", access_token, { expires: 1 });
        Cookies.set("refresh_token", refresh_token, { expires: 1 });
        Cookies.set("time_refresh", new Date(newTime).toISOString(), {
          expires: 1,
        });
      }
    }
  }
  return req;
});

export default axiosInterceptor;
