"use client";
import React, {createContext, useContext, useEffect, useState} from 'react';
import axiosInstance, {SetupAxiosInterceptors} from './axiosInstance';

const AxiosContext = createContext(axiosInstance);
const TokenContext = createContext({
    setAccessToken: (token: string | null) => {},
});

export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [accessToken, setAccessToken] = useState<string | null>(localStorage.getItem("accessToken"));

    useEffect(() => {
        if (accessToken) {
            axiosInstance.defaults.headers.Authorization = `Bearer ${accessToken}`;
            SetupAxiosInterceptors(accessToken);
            console.log("[debug] Updated accessToken:", accessToken);
        }
    }, [accessToken]);

    return (
        <AxiosContext.Provider value={axiosInstance}>
            <TokenContext.Provider value={{ setAccessToken }}>
                {children}
            </TokenContext.Provider>
        </AxiosContext.Provider>
    );
};

// Custom hook to use Axios instance
export const useAxios = () => {
    return useContext(AxiosContext);
};

// Custom hook to manage access token
export const useToken = () => {
    return useContext(TokenContext);
};