import { LoginParams, LoginResponse } from '@/entities/user/model/types';
import { StorageKeys } from '@/shared/constants/local-storage';
import { setLocalStorage } from '@/shared/lib/web-view-bridge';
import { useLoginMutation } from '@/entities/user/api/use-login-mutation';
import { useStore } from '~/shared/model/store';
import { useAppBridge } from '@/hooks';

export const useUserInfo = () => {
  const { mutateAsync: login } = useLoginMutation();
	const { 
		isNativeEnvironment,
		requestToken,
		logout
	} = useAppBridge();
	const callLogin = async (params?: LoginParams) => {
		try{
			useStore.getState().UserStore.resetUserInfo();
			
			if(isNativeEnvironment){
				const result: LoginResponse = await requestToken();
				if(!result) {
					// 토큰이 null인 경우 로그아웃 처리
					console.error('Token is null, performing logout');
					useStore.getState().UserStore.resetUserInfo();
					logout();
					return;
				}
				updateUserData(result);
			}
			else{
				// 개발용 ...
				if(params){
					const result: LoginResponse = await login(params);
					result.usrid = params.id;
					updateUserData(result);
				}
			}	
		}
		catch(error: any){
			console.error('Failed to request token:', error);
      useStore.getState().UserStore.resetUserInfo();
			logout();
		}
	};

	const updateUserData = (data: LoginResponse) => {
		console.log('updateUserData ==> ['+JSON.stringify(data)+']');
		setLocalStorage(StorageKeys.TokenType, data.tokenType);
		setLocalStorage(StorageKeys.AccessToken, data.accessToken);
		setLocalStorage(StorageKeys.RefreshToken, data.refreshToken);
		setLocalStorage(StorageKeys.AccessTokenExpiresIn, data.accessTokenExpiresIn);
		setLocalStorage(StorageKeys.RefreshTokenExpiresIn, data.refreshTokenExpiresIn);
		setLocalStorage(StorageKeys.MenuGrants, data.menuGrants);
		setLocalStorage(StorageKeys.ClientAddressIP, data.clientAddressIP);
		setLocalStorage(StorageKeys.Requires2FA, data.requires2FA);
		setLocalStorage(StorageKeys.Usrid, data.usrid);

		if(isNativeEnvironment){
			setLocalStorage(StorageKeys.DeviceId, data.deviceId);
			setLocalStorage(StorageKeys.AppVersion, data.appVersion);
		}

		useStore.getState().UserStore.setUserInfo({
			...data
		}); 
	};

	return {
		callLogin,
		updateUserData
	} 		
}