import type { Edges } from "@/types/requests/utils/edges"
import type { NodeRefs } from "@/types/requests/utils/refs"
import type { Lang } from "@/constants/languages"

/**
 * Function to generate tag for initial refs request
 *
 * @param lang Lang
 * @param identifier Should be uid for all pages and content_type_uid for
 *                   everything else
 * @param affix possible extra value to add to string, e.g lang:identifier:breadcrumbs:refs
 *              as it is the same entity as the actual page tag otherwise
 * @returns string
 */
export function generateRefsResponseTag(
  lang: Lang,
  identifier: string,
  affix?: string
) {
  if (affix) {
    return `${lang}:${identifier}:${affix}:refs`
  }
  return `${lang}:${identifier}:refs`
}

/**
 * Function to generate all tags to references on entity
 *
 * @param lang Lang
 * @param contentTypeUid content_type_uid of reference
 * @param uid system.uid of reference
 * @returns string
 */
export function generateRefTag(
  lang: Lang,
  contentTypeUid: string,
  uid: string
) {
  return `${lang}:ref:${contentTypeUid}:${uid}`
}

/**
 * Function to generate tag for entity being requested
 *
 * @param lang Lang
 * @param uid system.uid of entity
 * @param affix possible extra value to add to string, e.g lang:uid:breadcrumbs
 *              as it is the same entity as the actual page tag otherwise
 * @returns string
 */
export function generateTag(lang: Lang, uid: string, affix?: string) {
  if (affix) {
    return `${lang}:${uid}:${affix}`
  }

  return `${lang}:${uid}`
}

export function generateTags(lang: Lang, connections: Edges<NodeRefs>[]) {
  return connections
    .map((connection) => {
      return connection.edges.map(({ node }) => {
        return generateRefTag(
          lang,
          node.system.content_type_uid,
          node.system.uid
        )
      })
    })
    .flat()
}
