import { GetContactConfig } from "@/lib/graphql/Query/ContactConfig.graphql"
import { request } from "@/lib/graphql/request"
import { internalServerError, notFound } from "@/server/errors/trpc"
import { contentstackProcedure, router } from "@/server/trpc"

import { type ContactConfigData, validateContactConfigSchema } from "./output"

export const contactConfigQueryRouter = router({
  get: contentstackProcedure.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) {
      throw internalServerError(validatedContactConfigConfig.error)
    }

    return validatedContactConfigConfig.data.all_contact_config.items[0]
  }),
})
