import axios from "axios";
import { commonStore, loadingStore } from "@/stores/commonStore";
import { storage } from "@/utils/storage";
import router from "@/router";

const loading = loadingStore();

const API_URL = import.meta.env.VITE_APP_API_SERVER_URL;
export const request = {
  post: (uri: string, param: any): any => {
    return axios.post(`${API_URL}${uri}`, param);
  },
  get: (uri: string, param: any, config?: any): any => {
    return axios.get(`${API_URL}${uri}`, { params: param, ...config });
  },
  getsize: (uri: string): any => {
    return axios.get(`${API_URL}${uri}`);
  },
  delete: (uri: string, param: any): any => {
    return axios.delete(`${API_URL}${uri}`, param);
  },
  put: (uri: string, param: any): any => {
    return axios.put(`${API_URL}${uri}`, param);
  },
  getFile: (uri: string, param: any): any => {
    return axios.get(`${API_URL}${uri}`, {
      params: param,
      responseType: "blob",
    });
  },
  postFile: (uri: string, param: any, attachment: any, progress: any): any => {
    const formData = new FormData();

    for (const key in attachment) {
      if (Object.prototype.hasOwnProperty.call(attachment, key)) {
        const value = attachment[key];

        if (Array.isArray(value)) {
          for (const file of value) {
            formData.append(key, file);
          }
        } else {
          formData.append(key, value);
        }
      }
    }
    formData.append("param", JSON.stringify(param));

    return axios.post(`${API_URL}${uri}`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      onUploadProgress: progress,
    });
  },
  postWithConfig: (uri: string, data: any, config?: any): any => {
    return axios.post(`${API_URL}${uri}`, data, config);
  },
  postMultipartWithParams: (uri: string, form: FormData, params?: any): any => {
    return axios.post(`${API_URL}${uri}`, form, {
      params,
      headers: { "Content-Type": "multipart/form-data" },
    });
  },

  postResponseFile: (
    uri: string,
    param: any,
    responseParam: any,
    attachment: any,
    progress: any,
  ): any => {
    const formData = new FormData();
    for (const key in attachment) {
      if (Object.prototype.hasOwnProperty.call(attachment, key)) {
        const value = attachment[key];
        if (Array.isArray(value)) {
          for (const file of value) {
            formData.append(key, file);
          }
        }
      }
    }
    formData.append("param", JSON.stringify(param));
    formData.append("responseParam", JSON.stringify(responseParam));

    return axios.post(`${API_URL}${uri}`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      onUploadProgress: progress,
    });
  },
  postNoParam: (uri: string): any => {
    return axios.post(`${API_URL}${uri}`, null);
  },
};

axios.defaults.headers.common["Access-Control-Allow-Origin"] = "*";
axios.interceptors.request.use(
  (config) => {
    loading.setLoading(true);

    const token = storage.getToken();
    const refresh = storage.getRefreshToken();

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    if (token) (config.headers as any)["cuuva-jwt"] = token;
    if (refresh) (config.headers as any)["cuuva-jwt-refresh"] = refresh;

    return config;
  },
  (error) => {
    loading.setLoading(false);
    const store = commonStore();
    store.setSnackbarMsg({
      text: "에러가 발생하였습니다.",
      color: "red",
      result: 500,
    });

    return Promise.reject(error);
  },
);

axios.interceptors.response.use(
  (response) => {
    loading.setLoading(false);
    return response;
  },
  (error) => {
    loading.setLoading(false);

    const store = commonStore();
    store.setSnackbarMsg({
      text: "에러가 발생하였습니다.",
      color: "red",
      result: 500,
    });

    return Promise.reject(error);
  },
);
