import { createContext, PropsWithChildren, useContext } from "react";
import { useStorageState } from '@/src/context/UseStorageState';

type TokenType = {
    token: string | null;
    setToken: (token: string | null) => void;
    isLoading: boolean;
}

const TokenContext = createContext<TokenType>( {
    setToken: () => {
    },
    token: null,
    isLoading: true,
} );

export const useToken = () => useContext( TokenContext );

export function AppProvider({ children }: PropsWithChildren) {
    const [ [ isLoading, token ], setSession ] = useStorageState( 'appToken' );

    const tokenContext: TokenType = {
        token,
        setToken: (token) => {
            setSession( token );
        },
        isLoading,
    };

    return <TokenContext.Provider value={tokenContext}>{children}</TokenContext.Provider>;
}