import { loginUser, getUserInfo } from '@/api/autoshopee/user';
import { getUserInfo as getStorageUserInfo } from './index';
import {
  storageProfileId,
  storageUserToken,
  storageUserData,
  storageUserId,
  storageUserPlan,
} from '@/plugins/storage/items';
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 storageProfileId.getValue();
      const loginResult = await loginUser(
        storageUser.username,
        storageUser.password,
        profileId || '',
      );

      if (loginResult.success && loginResult.token && loginResult.data) {
        await storageUserToken.setValue(loginResult.token);
        await storageUserData.setValue(loginResult.data);
        await storageUserId.setValue(loginResult.data._id);

        if (loginResult.data.extensionPlan) {
          await storageUserPlan.setValue(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;
  }
};
