import axios, { type AxiosRequestConfig } from "axios";
import { AUTH_FLAG } from "@/hooks/useAuth";

export const publicApi = axios.create({
  withCredentials: true,
  baseURL: '',
});

publicApi.interceptors.response.use(
  (res) => res,
  (error) => {
    const url = error.config?.url ?? '';
    if (
      error.response?.status === 401 &&
      error.response?.data?.code === "user_not_found" &&
      !url.includes("/api/account/logout/")
    ) {
      localStorage.removeItem(AUTH_FLAG);
      window.location.href = "/social/login";
    }
    return Promise.reject(error);
  }
);

const pendingRequests = new Map();

export const publicMutator = async <T>(config: AxiosRequestConfig): Promise<T> => {
  const requestKey = `${config.method}_${config.url}_${JSON.stringify(config.data || '')}`;

  if (pendingRequests.has(requestKey)) {
    return pendingRequests.get(requestKey);
  }

  const requestPromise = (async () => {
    try {
      const response = await publicApi.request<T>(config);
      return response.data;
    } finally {
      pendingRequests.delete(requestKey);
    }
  })();

  pendingRequests.set(requestKey, requestPromise);

  return requestPromise;
};
