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 { FindByIdVariables } from './types';

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

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