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

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

  function findById(id: string, variables?: FindByIdVariables) {
    loading.set(true);
    return runInInjectionContext(injector, () =>
      queryFindById<T>(statement, key, id, fields, variables),
    ).pipe(
      tap((data) => item.set(data)),
      finalize(() => loading.set(false)),
    );
  }

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