import type { DocumentNode } from "graphql"

export function getOperationName(query: string | DocumentNode): string {
  let operationName = ""

  if (typeof query === "string") {
    const operationRegex = /(query|mutation|subscription)\s+(\w+)/
    const match = query.match(operationRegex)
    if (match && match[2]) {
      operationName = match[2]
    }
  } else {
    const opDefinition = query.definitions.find(
      (def) => def.kind === "OperationDefinition" && def.name
    )
    if (opDefinition && "name" in opDefinition && opDefinition.name) {
      operationName = opDefinition.name.value
    }
  }

  return operationName ?? "AnonymousOperation"
}
