import {
  getHeader,
  getRequestHost,
  defineEventHandler,
  getRequestURL,
} from "h3";

export default defineEventHandler(async (event) => {
  const url = getRequestURL(event);

  // 정적 자산, API, 파비콘 등은 제외하고 페이지 요청만 처리
  if (
    url.pathname.startsWith("/api/") ||
    url.pathname.startsWith("/_nuxt/") ||
    url.pathname.startsWith("/favicon") ||
    url.pathname.includes(".") ||
    url.pathname.startsWith("/_")
  ) {
    return;
  }

  const host =
    (getHeader(event, "host") || getRequestHost(event)).toString() || "";
  const baseDomain = process.env.BASE_DOMAIN || ".onstove.com";
  const isGameAliasExtractable = host.includes(baseDomain);

  if (isGameAliasExtractable) {
    const gameAlias = host.split(".")[0];

    if (gameAlias && gameAlias !== "www") {
      event.context.gameAlias = gameAlias;
    }
  }

  // gameData를 직접 가져와서 context에 저장 (API 호출 없이)
  try {
    const config = useRuntimeConfig();
    const stoveApiBaseUrl = config.public.stoveApiUrl;
    const apiUrl = `${stoveApiBaseUrl}/pub-comm/v1.0/template/game`;

    // URL의 첫 번째 path를 lang_code로 사용 (파비콘, API 경로 제외)
    const url = getRequestURL(event);
    const pathSegments = url.pathname
      .split("/")
      .filter(
        (segment) =>
          segment &&
          !segment.includes("favicon") &&
          !segment.includes("api") &&
          !segment.startsWith("_")
      );
    const langCode = pathSegments[0] || "ko";

    const queryParams: Record<string, string> = {
      game_alias: event.context.gameAlias || "",
      lang_code: langCode,
    };

    const response = await $fetch(apiUrl, {
      query: queryParams,
    });

    if (response?.code === 0 && "value" in response) {
      event.context.gameData = response.value;
    }
  } catch (error) {
    console.error("gameData load error:", error);
  }
});
