import { loginUser, getUserInfo } from '@/api/autoshopee/user';
import { getUserInfo as getStorageUserInfo } from './index';
import { userSetting, indentifySetting } from '@/plugins/setting';
import { loggerBackground } from '@/plugins/logger';

export const userSessionRefresh = async () => {
  try {
    const storageUser = await getStorageUserInfo();

    if (!storageUser.isAuthed || !storageUser.username || !storageUser.password) {
      return false;
    }

    let apiResult;

    try {
      apiResult = await getUserInfo();
    } catch (error) {
      const status = error?.response?.status;
      const data = error?.response?.data;

      if (status === 403 || (data && data.error === 403)) {
        apiResult = { error: 403 };
      } else {
        throw error;
      }
    }

    if (apiResult && apiResult.error === 403) {
      const profileId = await indentifySetting.profileId.getSync();
      const loginResult = await loginUser(
        storageUser.username,
        storageUser.password,
        profileId || '',
      );

      if (loginResult.success && loginResult.token && loginResult.data) {
        await userSetting.userToken.set(loginResult.token);
        await userSetting.userData.set(loginResult.data);
        await userSetting.userId.set(loginResult.data._id);

        if (loginResult.data.extensionPlan) {
          await userSetting.userExtensionPlan.set(loginResult.data.extensionPlan);
        }

        loggerBackground.log('USER_SESSION_REFRESH_SUCCESS', { username: storageUser.username });
        return true;
      }

      loggerBackground.error({
        msg: 'USER_SESSION_REFRESH_LOGIN_FAILED',
        username: storageUser.username,
        result: loginResult,
      });
    }

    return false;
  } catch (error) {
    loggerBackground.error({
      msg: 'USER_SESSION_REFRESH_ERROR',
      error,
    });
    return false;
  }
};
