import { inject } from '@angular/core';
import type { DefaultContext } from '@apollo/client/core';
import { Apollo } from 'apollo-angular';
import type { DocumentNode } from 'graphql';
import { map, type Observable } from 'rxjs';
import { parseGqlFields } from '../parse-gql-fields';
import type { FetchVariables } from './types';

export function queryFind<T>(
  statement: DocumentNode,
  key: string,
  fields?: string,
  variables?: FetchVariables,
): Observable<T | null> {
  const apollo = inject(Apollo);
  const query = fields
    ? parseGqlFields(statement, fields, variables?.query ?? {}, variables?.constraint ?? {})
    : statement;

  return apollo
    .query<Record<string, T>>({
      query,
      variables,
      context: { headers: variables?.headers } as DefaultContext,
    })
    .pipe(map((result) => result.data?.[key] ?? null));
}
