import { GetLoyaltyPageMetaData } from "@/lib/graphql/Query/LoyaltyPage/MetaData.graphql"
import { contentstackExtendedProcedureUID, router } from "@/server/trpc"

import {
  type GetLoyaltyPageMetaDataData,
  getLoyaltyPageMetadataSchema,
} from "./output"
import { getMetaData, getResponse, type Variables } from "./utils"

import { PageTypeEnum } from "@/types/requests/pageType"

async function getLoyaltyPageMetaData(variables: Variables) {
  const response = await getResponse<GetLoyaltyPageMetaDataData>(
    GetLoyaltyPageMetaData,
    variables
  )

  const validatedMetadata = getLoyaltyPageMetadataSchema.safeParse(
    response.data
  )

  if (!validatedMetadata.success) {
    console.error(
      `Failed to validate Loyaltypage MetaData Data - (uid: ${variables.uid})`
    )
    console.error(validatedMetadata.error)
    return null
  }

  return getMetaData(validatedMetadata.data.loyalty_page)
}

export const metaDataQueryRouter = router({
  get: contentstackExtendedProcedureUID.query(async ({ ctx }) => {
    const variables = {
      locale: ctx.lang,
      uid: ctx.uid,
    }

    switch (ctx.contentType) {
      case PageTypeEnum.loyaltyPage:
        return await getLoyaltyPageMetaData(variables)
      default:
        return null
    }
  }),
})
