import { localStorage } from "@applicaster/zapp-react-native-bridge/ZappStorage/LocalStorage";
import { sessionStorage } from "@applicaster/zapp-react-native-bridge/ZappStorage/SessionStorage";

const versionNameKey = "version_name";

const SessionStorageKeys = {
  total_session_number: "total_session_number",
  total_sessions_for_current_version: "total_sessions_for_current_version",
  current_monitoring_session_version: "current_monitoring_session_version",
};

async function setTotalSessionNumber() {
  const currentSession =
    (await localStorage.getItem(SessionStorageKeys.total_session_number)) || 0;

  await localStorage.setItem(
    SessionStorageKeys.total_session_number,
    currentSession + 1
  );
}

async function setTotalSessionForCurrentVersion() {
  const applicationVersionNamePromise = sessionStorage.getItem(versionNameKey);

  const storedVersionNamePromise = localStorage.getItem(
    SessionStorageKeys.current_monitoring_session_version
  );

  const [applicationVersionName, storedVersionName] = await Promise.all([
    applicationVersionNamePromise,
    storedVersionNamePromise,
  ]);

  let currentSession = 1;

  if (applicationVersionName !== storedVersionName) {
    await localStorage.setItem(
      SessionStorageKeys.current_monitoring_session_version,
      applicationVersionName
    );
  } else if (applicationVersionName === storedVersionName) {
    currentSession =
      (await localStorage.getItem(
        SessionStorageKeys.total_sessions_for_current_version
      )) || currentSession;

    currentSession += 1;
  }

  await localStorage.setItem(
    SessionStorageKeys.total_sessions_for_current_version,
    currentSession
  );
}

export function updateSessionNumber() {
  return Promise.all([
    setTotalSessionNumber(),
    setTotalSessionForCurrentVersion(),
  ]);
}
