import React, { createContext, useContext, ReactNode } from 'react';
import { useAuth } from '../Hooks/useAuth';
import { ResourceBrowserSource, ResourceBrowserSourceWithConfig } from '../types';

interface AuthContextProps {
    authToken: string | null;
    isAuthenticated: boolean;
    login: () => void;
    refreshAccessToken: () => Promise<any>;
    alwaysUseResourceRequestProxy: boolean;
}

export const AuthContext = createContext<AuthContextProps | undefined>(undefined);

export const useAuthContext = (): AuthContextProps => {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error('useAuthContext must be used within an AuthProvider');
    }
    return context;
};

interface AuthProviderProps {
    children: ReactNode;
    authConfig?: ResourceBrowserSource | null;
}

export const AuthProvider = ({ children, authConfig }: AuthProviderProps) => {
    const authConfiguration = authConfig as ResourceBrowserSourceWithConfig;
    const auth = useAuth(authConfiguration?.configuration);

    if (!authConfiguration?.configuration) {
        return <>{children}</>;
    }

    return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>;
};
