import { Lang } from "@/constants/languages"
import { request } from "@/lib/graphql/request"
import { internalServerError, notFound } from "@/server/errors/trpc"

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

import { getMetaDataSchema, Page } from "../schemas/metadata"

export type Variables = {
  locale: Lang
  uid: string
}

export const affix = "metadata"

export async function getResponse<T>(query: string, variables: Variables) {
  const response = await request<T>(query, variables, {
    cache: "force-cache",
    next: {
      tags: [generateTag(variables.locale, variables.uid, affix)],
    },
  })
  if (!response.data) {
    throw notFound(response)
  }

  return response
}

export function getMetaData(page: Page) {
  const pageMetaData = {
    breadcrumbsTitle: page.web.breadcrumbs.title,
    title: page.web.seo_metadata.title,
    description: page.web.seo_metadata.description,
    imageConnection: page.web.seo_metadata.imageConnection,
    uid: page.system.uid,
  }
  const validatedMetaData = getMetaDataSchema.safeParse(pageMetaData)
  if (!validatedMetaData.success) {
    throw internalServerError(validatedMetaData.error)
  }

  return validatedMetaData.data
}
