import useGetCookie from "@/hooks/useGetCookie";
import axios from "axios";
const BASEURL = import.meta.env.VITE_API_BASEURL;

const instance = axios.create({
  baseURL: BASEURL,
  timeout: -1,
  headers: { Authorization: `Bearer ${useGetCookie("JWT-Authorization")}` },
});

// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
        const token = useGetCookie("JWT-Authorization");
        // 取得 building_guid 並加到 headers
        let buildingGuid = "";
        try {
          const cviBuilding = localStorage.getItem("EmpowerBuilding");
          if (cviBuilding) {
            const parsed = JSON.parse(cviBuilding);
            buildingGuid = parsed.building_guid || "";
          }
        } catch (e) {
          buildingGuid = "";
        }
        config.headers = {
          Authorization: `Bearer ${token}`,
          "X-Building-GUID": buildingGuid,
        };
        return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const { status, data, headers } = response;

    return {
      ...data,
    };
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    if (error.response && error.response.status === 401) {
      window.location.href = "/";
    }
    return Promise.reject(error);
  }
);

export const fileInstance = axios.create({
  baseURL: BASEURL,
  timeout: -1,
  headers: { Authorization: `Bearer ${useGetCookie("JWT-Authorization")}` },
});

// Add a request interceptor
fileInstance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
        const token = useGetCookie("JWT-Authorization");
        // 取得 building_guid 並加到 headers
        let buildingGuid = "";
        try {
          const cviBuilding = localStorage.getItem("EmpowerBuilding");
          if (cviBuilding) {
            const parsed = JSON.parse(cviBuilding);
            buildingGuid = parsed.building_guid || "";
          }
        } catch (e) {
          buildingGuid = "";
        }
        config.headers = {
          Authorization: `Bearer ${token}`,
          "X-Building-GUID": buildingGuid,
        };
        return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
fileInstance.interceptors.response.use(
  async function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const { status, data, headers } = response;

    console.log("@@", status, data, headers);

    let errorData = {};
    if (headers["content-type"] === "application/json; charset=utf-8") {
      const blob = new Blob([data]);
      const blobText = await blob.text();
      errorData = JSON.parse(blobText);
    }

    return headers["content-disposition"]
      ? { data, code: "0000", headers }
      : {
          ...errorData,
        };
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

export default instance;
