import axios, { ResponseType } from 'axios';
import { useAuthStore } from '../store/auth';

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(
    (config) => {
        const token = useAuthStore.getState().token;
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

export const fetcher = (url: string, baseURL?: string, responseType?: ResponseType) => axiosInstance.get(url, {
    baseURL: baseURL || import.meta.env.VITE_API_NEST_URL,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: responseType ? responseType : "json"
}).then(res => res.data)

export default axiosInstance;