export const MATCH_RETURN_SNAPSHOT_KEY = "match-return-snapshot";

function getMatchId(battleInfo) {
  return battleInfo?.matchId || battleInfo?.id || "";
}

function getBattlePageUrl(battleInfo, matchId) {
  const page =
    Number(battleInfo?.mode) <= 3
      ? "/pages/team-battle/index"
      : "/pages/melee-battle";
  return `${page}?fromReturn=1&battleId=${encodeURIComponent(String(matchId))}`;
}

export function takeMatchReturnSnapshot() {
  const snapshot = uni.getStorageSync(MATCH_RETURN_SNAPSHOT_KEY);
  if (snapshot) uni.removeStorageSync(MATCH_RETURN_SNAPSHOT_KEY);
  return snapshot && typeof snapshot === "object" ? snapshot : null;
}

export async function returnToBattle(battleInfo, navigate) {
  const matchId = getMatchId(battleInfo);
  if (!battleInfo || !matchId || !battleInfo.serverAddr) {
    uni.showToast({
      title: "比赛连接信息异常",
      icon: "none",
    });
    return false;
  }

  uni.setStorageSync(MATCH_RETURN_SNAPSHOT_KEY, battleInfo);
  await navigate(getBattlePageUrl(battleInfo, matchId));
  return true;
}
