import { commonFetch } from "#layers/utils/apiUtil";
import { usePageDataStore } from "#layers/stores/usePageDataStore";
import { useGetGameAlias } from "#layers/composables/useGetGameAlias";
import { usePathResolver } from "#layers/composables/usePathResolver";
import type { PageDataResponse } from "#layers/types/api/pageData";

export default defineNuxtRouteMiddleware(async (to, from) => {
  if (import.meta.server) {
    return;
  }

  const config = useRuntimeConfig();
  const store = usePageDataStore();
  const gameAlias = useGetGameAlias();
  const { getPathAfterLanguage } = usePathResolver();

  const stoveApiBaseUrl = config.public.stoveApiUrl;
  const apiUrl = `${stoveApiBaseUrl}/pub-comm/v1.0/template/page`;

  try {
    const pageUrl = getPathAfterLanguage(to.path);
    const queryParams: Record<string, string> = {
      game_alias: gameAlias,
      lang_code: "ko",
      page_url: pageUrl,
      _t: Date.now().toString(), // 캐시 무효화를 위한 타임스탬프
    };

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

    if (response?.code === 0 && "value" in response) {
      const cleanData = JSON.parse(JSON.stringify(response.value));
      store.setPageData(cleanData);
    } else {
      store.clearPageData();
    }
  } catch (error) {
    console.error(error);
    store.clearPageData();
  }
});
