import type { DocumentNode } from 'graphql';
import gql from 'graphql-tag';

interface HasAttributes {
  readonly attributes?: string[];
  readonly [key: string]: unknown;
}

export const parseGqlFields = (
  graphqlStatement: DocumentNode,
  fields: string,
  ...queryStatements: HasAttributes[]
): DocumentNode => {
  let attributes: string[] = [];
  for (const queryStatement of queryStatements) {
    if (Array.isArray(queryStatement.attributes)) {
      attributes = [...new Set([...attributes, ...queryStatement.attributes])];
    }
  }

  const source = graphqlStatement.loc?.source.body ?? '';

  if (attributes.length > 0) {
    return gql`
      ${source.replace('#FIELDS', attributes.join('\n'))}
    `;
  }

  return gql`
    ${source.replace('#FIELDS', fields)}
  `;
};
