import axios from "axios";
import Swal from "sweetalert2";

const baseURL = import.meta.env.VITE_API_SERVER;

const instance = axios.create({
  baseURL,
  withCredentials: true,
});

// axios khusus refresh
const refreshApi = axios.create({
  baseURL,
  withCredentials: true,
});


instance.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;

    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      try {
        console.log("🔄 Refresh token dipanggil...");
        const refreshRes = await refreshApi.post("/auth/refresh-token");

        const newAccessToken = refreshRes.data.data.accessToken;
        localStorage.setItem("token", newAccessToken);

        // update token di header
        instance.defaults.headers.common["Authorization"] = `Bearer ${newAccessToken}`;
        originalRequest.headers["Authorization"] = `Bearer ${newAccessToken}`;

        return instance(originalRequest);
      } catch (refreshError) {
        console.error("Refresh token gagal:", refreshError);
        localStorage.clear();
        window.location.href = "/signin";
      }
    }

    return Promise.reject(error);
  }
);

async function ApiRequest({
  method = "GET",
  params = {},
  prefix = "/",
  token = true,
} = {}) {
  const isFormData = params instanceof FormData;

  const request = {
    method,
    url: prefix,
    data: params,
    headers: {
      "Accept-Language": "en_US",
      ...(isFormData ? {} : { "Content-Type": "application/json" }),
    },
  };

  const rawToken = localStorage.getItem("token");
  if (token && rawToken) {
    request.headers["Authorization"] = `Bearer ${rawToken.replace(/"/g, "")}`;
  }

  try {
    const response = await instance(request);
    return { ...response, error: false };
  } catch (error) {
    const status = error?.response?.status || 500;
    const message = error?.response?.data?.message || error.message || "Something Wrong";

    if (status !== 401) {
      await cekError(status, message);
    }

    return { ...error.response, error: true };
  }
}

async function cekError(status, message = "") {
  if (status === 403) {
    await Swal.fire({
      icon: "warning",
      title: "Forbidden",
      text: message,
    });
  } else if (status >= 500) {
    await Swal.fire({
      icon: "error",
      title: "Server Error",
      text: message,
    });
  } else {
    await Swal.fire({
      icon: "warning",
      title: "Peringatan",
      text: message,
    });
  }
}

const SendRequest = async (queryParams) => {
  try {
    const response = await ApiRequest(queryParams);
    return response?.data || [];
  } catch (error) {
    console.error("Request error:", error);
    await Swal.fire({
      icon: "error",
      text: error.message || "Something went wrong",
    });
    return [];
  }
};

export { ApiRequest, SendRequest };
