import { inject, Injector, runInInjectionContext, signal } from '@angular/core';
import type { DocumentNode } from 'graphql';
import { finalize, tap } from 'rxjs';
import type { DataTableData } from '../../../components/data-table/types';
import { queryPaginate } from '../../../modules/graphql/fetchers/query-paginate';
import type { FetchVariables } from '../../../modules/graphql/fetchers/types';

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

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

  return {
    paginate,
    pagination: pagination.asReadonly(),
    loading: loading.asReadonly(),
  };
}
