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

export function useGraphqlGet<T>(statement: DocumentNode, key: string, fields?: string) {
  const injector = inject(Injector);
  const items = signal<T[]>([]);
  const loading = signal(false);

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

  return {
    get,
    items: items.asReadonly(),
    loading: loading.asReadonly(),
  };
}
