import axios, { AxiosRequestConfig } from 'axios';
import useLocationInfo from '../../hooks/useLocationInfo';
import { accountApiUrl, accountClient } from '../axios';
import { RefreshModel } from '../models/AccountTypes';
import { LoadSessionExpireDate, SetSessionExpireDate } from '../user/localStorage';
import useAuth from './useAuth';
import GetUser from '../UserApi';

export type AuthenticationResult = {
    accessToken: string
    sessionExpireDate: string
}

export default function useRefreshToken() {
	const { setAccessToken } = useAuth();
	// const [ user, setUser ] = useAtom(userAtom);
	const { getLocationInfo } = useLocationInfo();

	const refresh =  async () => {
		const refreshToken = LoadSessionExpireDate();
		// console.log(`expireDate: ${refreshToken}`);
		// if (refreshToken == null) return Promise.reject("Refresh token not found");
		if (refreshToken == null) return null;
		const locationInfo = await getLocationInfo();
		try{
			const response = await axios.post<AuthenticationResult | null>(`${accountApiUrl}refresh`, {
				// refreshToken: refreshToken,
				ip: locationInfo?.ip,
			} as RefreshModel,
			{
				withCredentials : true,
			} as AxiosRequestConfig);
			const tokens = response.data;
			// console.log(`NEW ACCESS TOKEN: ${tokens?.accessToken}`);
			// console.log(`refresh: tok: ..${tokens?.accessToken?.toString().slice(-5)}, refr:..${tokens?.refreshToken.slice(-5)}, oldRefr:..${refreshToken.slice(-5)}`);
			let accessToken = tokens?.accessToken ?? null
			const loadedUser = await GetUser(accessToken);
			// console.log('loadedUser');
			// console.log(loadedUser);
			// setAuth(loadedUser);
			// console.log(`tokens?.refreshToken: ${tokens?.refreshToken}`);
			accessToken = loadedUser?.isAuthenticated ? accessToken : null;
			SetSessionExpireDate(loadedUser?.isAuthenticated && tokens != null ? tokens?.sessionExpireDate : null);
			setAccessToken(accessToken);
			// console.log('accessToken');
			// console.log(accessToken);
			// return Promise.resolve(tokens?.accessToken ?? null);
			return accessToken;
		}
		catch (ex) {
			console.log('Refresh failed:');
			console.log('ex:');
			console.error(ex);
			setAccessToken(null);
			//navigate to login
			SetSessionExpireDate(null);
		}
		
		return null;
	}
	return refresh;
}