import { publicProcedure, router } from "@/server/trpc"

import { getUidAndContentTypeByPath } from "@/services/cms/getUidAndContentTypeByPath"

import { getNonContentstackUrls } from "../metadata/output"
import { getLanguageSwitcherInput } from "./input"
import { getUrlsOfAllLanguages } from "./utils"

import type { LanguageSwitcherData } from "@/types/requests/languageSwitcher"

export const languageSwitcherQueryRouter = router({
  get: publicProcedure
    .input(getLanguageSwitcherInput)
    .query(async ({ input }) => {
      const { pathName, lang } = input
      const { uid, contentType } = await getUidAndContentTypeByPath(pathName)
      let urls: LanguageSwitcherData | null = null

      if (!uid || !contentType) {
        urls = getNonContentstackUrls(lang, pathName)
      } else {
        urls = await getUrlsOfAllLanguages(lang, uid, contentType)
      }

      return {
        lang,
        urls,
      }
    }),
})
