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

// --- 請求攔截器的共用邏輯 ---
const requestInterceptor = (config) => {
  // 確保 headers 物件存在
  if (!config.headers) {
    config.headers = {};
  }

  // 1. 取得並附加最新的 Token
  const token = useGetCookie("JWT-Authorization");
  if (token) {
    // 正確做法：修改屬性，而不是覆蓋整個物件
    config.headers.Authorization = `Bearer ${token}`;
  }

  // 2. 取得並附加選定的建築物 GUID
  const storedBuilding = localStorage.getItem("CviBuilding");
  if (storedBuilding) {
    try {
      const buildingObject = JSON.parse(storedBuilding);
      if (buildingObject && buildingObject.building_guid) {
        // 與後端約定好要用哪個標頭，這裡使用 'X-Building-GUID' 作為範例
        config.headers["X-Building-GUID"] = buildingObject.building_guid;
      }
    } catch (e) {
      console.error("解析 localStorage 中的 CviBuilding 失敗:", e);
    }
  }
  return config;
};

const requestErrorInterceptor = (error) => {
  return Promise.reject(error);
};


// --- 一般 API 實例 ---
const instance = axios.create({
  baseURL: BASEURL,
  timeout: 10000, // 建議設定超時
  // 移除靜態 headers
});

// 使用共用的攔截器
instance.interceptors.request.use(requestInterceptor, requestErrorInterceptor);

// 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 { data } = 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);
  }
);


// --- 檔案處理 API 實例 ---
export const fileInstance = axios.create({
  baseURL: BASEURL,
  timeout: -1,
  // 移除靜態 headers
});

// 使用共用的攔截器
fileInstance.interceptors.request.use(requestInterceptor, requestErrorInterceptor);

// 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;
