import { inject, Injector, runInInjectionContext, signal } from '@angular/core';
import type { DocumentNode } from 'graphql';
import { finalize, tap } from 'rxjs';
import { queryFind } from '../../../modules/graphql/fetchers/query-find';
import type { FetchVariables } from '../../../modules/graphql/fetchers/types';

export function useGraphqlFind<T>(statement: DocumentNode, key: string, fields?: string) {
  const injector = inject(Injector);
  const item = signal<T | null>(null);
  const loading = signal(false);

  function find(variables?: FetchVariables) {
    loading.set(true);
    return runInInjectionContext(injector, () =>
      queryFind<T>(statement, key, fields, variables),
    ).pipe(
      tap((data) => item.set(data)),
      finalize(() => loading.set(false)),
    );
  }

  return {
    find,
    item: item.asReadonly(),
    loading: loading.asReadonly(),
  };
}
