import axios from "axios";
import useAuthStore from "@/stores/useAuthStore";
import useAuthPopup from "@/stores/useAuthPopup";

const useApiClient = () => {
    const { getToken } = useAuthStore();
    const authPopup = useAuthPopup();

    const apiClient = axios.create({
        baseURL: "https://api.travelmarine.ru",
        headers: {
            "Content-Type": "application/json",
        },
    });

    apiClient.interceptors.request.use(
        (config) => {
            const token = getToken();

            if (token) {
                config.headers.Authorization = `Token ${token}`;
            }

            return config;
        },
        (error) => {
            return Promise.reject(error);
        }
    );

    apiClient.interceptors.response.use(
        (response) => response,
        (error) => {
            if (error.response?.status === 401) {
                console.error("Authentication error:", error);
                authPopup.open();
            }
            if (error.response?.status === 400 || error.response?.status === 429) {
                const data = error.response?.data;
                const message =
                    typeof data === "object" && data !== null
                        ? (data.message ?? data.error ?? data.detail ?? data.msg)
                        : typeof data === "string"
                          ? data
                          : undefined;
                if (message && typeof message === "string") {
                    return Promise.reject(new Error(message));
                }
            }
            return Promise.reject(error);
        }
    );

    return apiClient;
};

export default useApiClient;
