import { GetContactConfig } from "@/lib/graphql/Query/ContactConfig.graphql"
import {
  GetCurrentFooter,
  GetCurrentFooterRef,
} from "@/lib/graphql/Query/CurrentFooter.graphql"
import {
  GetCurrentHeader,
  GetCurrentHeaderRef,
} from "@/lib/graphql/Query/CurrentHeader.graphql"
import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"
import {
  contentstackBaseProcedure,
  publicProcedure,
  router,
} from "@/server/trpc"

import { generateTag } from "@/utils/generateTag"

import { langInput } from "./input"
import {
  type ContactConfigData,
  FooterDataRaw,
  FooterRefDataRaw,
  HeaderData,
  HeaderDataRaw,
  HeaderRefDataRaw,
  validateContactConfigSchema,
  validateFooterConfigSchema,
  validateHeaderConfigSchema,
} from "./output"

export const baseQueryRouter = router({
  contact: contentstackBaseProcedure.query(async ({ ctx }) => {
    const { lang } = ctx

    const response = await request<ContactConfigData>(GetContactConfig, {
      locale: lang,
    })

    if (!response.data) {
      throw notFound(response)
    }

    const validatedContactConfigConfig = validateContactConfigSchema.safeParse(
      response.data
    )

    if (!validatedContactConfigConfig.success) {
      console.info(
        `Failed to validate Contact Config Data - (lang: ${ctx.lang})`
      )
      console.error(validatedContactConfigConfig.error)
      return null
    }

    return validatedContactConfigConfig.data.all_contact_config.items[0]
  }),
  header: contentstackBaseProcedure
    .input(langInput)
    .query(async ({ input }) => {
      const responseRef = await request<HeaderRefDataRaw>(GetCurrentHeaderRef, {
        locale: input.lang,
      })

      const response = await request<HeaderDataRaw>(
        GetCurrentHeader,
        { locale: input.lang },
        {
          tags: [
            generateTag(
              input.lang,
              responseRef.data.all_current_header.items[0].system.uid
            ),
          ],
        }
      )

      if (!response.data) {
        throw notFound(response)
      }

      const validatedHeaderConfig = validateHeaderConfigSchema.safeParse(
        response.data
      )

      if (!validatedHeaderConfig.success) {
        console.info(`Failed to validate Header - (lang: ${input.lang})`)
        console.error(validatedHeaderConfig.error)
        return null
      }

      const logo =
        validatedHeaderConfig.data.all_current_header.items[0].logoConnection
          .edges?.[0]?.node

      return {
        ...validatedHeaderConfig.data.all_current_header.items[0],
        logo,
      } as HeaderData
    }),
  footer: contentstackBaseProcedure
    .input(langInput)
    .query(async ({ input }) => {
      const responseRef = await request<FooterRefDataRaw>(GetCurrentFooterRef, {
        locale: input.lang,
      })

      const response = await request<FooterDataRaw>(
        GetCurrentFooter,
        {
          locale: input.lang,
        },
        {
          tags: [
            generateTag(
              input.lang,
              responseRef.data.all_current_footer.items[0].system.uid
            ),
          ],
        }
      )

      const validatedFooterConfig = validateFooterConfigSchema.safeParse(
        response.data
      )

      if (!validatedFooterConfig.success) {
        console.info(`Failed to validate Footer - (lang: ${input.lang})`)
        console.error(validatedFooterConfig.error)
        return null
      }

      return validatedFooterConfig.data.all_current_footer.items[0]
    }),
})
