const PENDING_INVITE_EMAIL_KEY = 'pending-invite-email';
const PENDING_INVITE_TOKEN_KEY = 'pending-invite-token';

export type PendingInvite = {
  email: string | null;
  token: string | null;
};

function getSessionStorage(): Storage | null {
  if (typeof window === 'undefined') {
    return null;
  }

  return window.sessionStorage;
}

export function setPendingInvite(invite: PendingInvite) {
  const storage = getSessionStorage();

  if (!storage) return;

  clearPendingInvite();

  if (invite.email) {
    storage.setItem(PENDING_INVITE_EMAIL_KEY, invite.email);
  }

  if (invite.token) {
    storage.setItem(PENDING_INVITE_TOKEN_KEY, invite.token);
  }
}

export function getPendingInvite(): PendingInvite {
  const storage = getSessionStorage();

  if (!storage) {
    return {
      email: null,
      token: null,
    };
  }

  return {
    email: storage.getItem(PENDING_INVITE_EMAIL_KEY),
    token: storage.getItem(PENDING_INVITE_TOKEN_KEY),
  };
}

export function clearPendingInvite() {
  const storage = getSessionStorage();

  if (!storage) return;

  storage.removeItem(PENDING_INVITE_EMAIL_KEY);
  storage.removeItem(PENDING_INVITE_TOKEN_KEY);
}

export async function acceptStoredPendingInvite(
  acceptPendingInvitations: (payload: { inviteToken?: string }) => Promise<unknown>
) {
  const pendingInvite = getPendingInvite();

  if (!pendingInvite.token) {
    await acceptPendingInvitations({});
    clearPendingInvite();
    return;
  }

  await acceptPendingInvitations({ inviteToken: pendingInvite.token });
  clearPendingInvite();
}
