import { connectMatchWebSocket } from "@/matchWebsocket";
import useStore from "@/store";

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

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

function getBattlePageUrl(battleInfo) {
  return Number(battleInfo?.mode) <= 3
    ? "/pages/team-battle/index?fromReturn=1"
    : "/pages/melee-battle?fromReturn=1";
}

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;
  }

  const store = useStore();
  uni.setStorageSync(MATCH_RETURN_SNAPSHOT_KEY, battleInfo);
  connectMatchWebSocket({
    serverAddr: battleInfo.serverAddr,
    matchId,
    userId: store.user?.id,
  });

  await navigate(getBattlePageUrl(battleInfo));
  return true;
}
