import { csrDecodedJWT } from "#layers/utils/jwtUtil";

/**
 * Stove 로그인
 */
export const csrGoStoveLogin = () => {
  const runtimeConfig = useRuntimeConfig();

  const loginUrl = runtimeConfig.public.stoveLoginUrl;
  const stoveGameId = runtimeConfig.public.stoveGameId;
  const stoveGameNo = runtimeConfig.public.stoveGameNo;
  const redirectUrl = encodeURIComponent(location.href);

  const url = `${loginUrl}?redirect_url=${redirectUrl}&inflow_path=${stoveGameId}&game_no=${stoveGameNo}`;
  location.href = url;
};

/**
 * Stove memberNo 조회
 */
export const csrGetStoveMemberNo = () => {
  let memberNo = 0;
  try {
    const suat = useCookie("SUAT");

    if (suat.value !== undefined && suat.value !== "") {
      const base64Payload = suat.value?.split(".")[1] ?? "";
      const decodeVal = csrDecodedJWT(base64Payload);
      memberNo = Number(`${decodeVal.member_no}`) ?? 0;
    } else {
      memberNo = 0;
    }
  } catch (e) {
    console.error("[Exception] stoveUtil.csrGetStoveMemberNo: ", e);
    return 0;
  }
  return memberNo;
};

/**
 * AccessToken 조회
 */
export const csrGetAccessToken = () => {
  let accessToken = "";
  try {
    const suat = useCookie("SUAT");

    if (suat.value !== undefined && suat.value !== "") {
      accessToken = `${suat.value || ""}`;
    } else {
      accessToken = "";
    }
  } catch (e) {
    console.error("[Exception] stoveUtil.csrGetAccessToken: ", e);
    return "";
  }
  return accessToken;
};

/**
 * 국가 코드 조회
 */
export const csrGetCountry = () => {
  let countryCode = "";
  try {
    const nnto = useCookie("NNTO");

    if (nnto.value !== undefined && nnto.value !== "") {
      countryCode = `${nnto.value || ""}`;
    } else {
      countryCode = "";
    }
  } catch (e) {
    console.error("[Exception] stoveUtil.csrGetCountry: ", e);
    return "";
  }
  return countryCode;
};
