import { commonFetch } from "#layers/utils/apiUtil";
import { getHeader } from "h3";
import type {
  GameDataResponse,
  GameDataValue,
} from "#layers/types/api/gameData";

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  const baseDomain = (config.public.baseDomain || ".onstove.com") as string;
  const stoveApiBaseUrl = config.public.stoveApiUrl;
  const apiUrl = `${stoveApiBaseUrl}/pub-comm/v1.0/template/game`;
  let gameAlias = "";

  try {
    // 미들웨어에서 설정한 gameAlias가 있다면 우선 사용
    if (event.context.gameAlias) {
      gameAlias = event.context.gameAlias;
    } else {
      const host = getHeader(event, "host") || "";
      const isGameAliasExtractable = host.includes(baseDomain);

      if (isGameAliasExtractable) {
        const subdomain = host.split(".")[0];
        if (subdomain && subdomain !== "www") {
          gameAlias = subdomain;
        }
      }
    }
  } catch (error) {
    console.log("gameAlias extraction error: ", error);
  }

  try {
    const queryParams: Record<string, string> = {
      game_alias: gameAlias,
      lang_code: "ko",
    };

    const response = (await commonFetch("GET", apiUrl, {
      query: queryParams,
    })) as GameDataResponse | null;

    if (response?.code === 0 && "value" in response) {
      event.context.gameData = response.value;
      return response.value as GameDataValue;
    }
  } catch (error) {
    console.error(error);
    return {};
  }
});
