import { inject, Injector, runInInjectionContext, signal } from '@angular/core';
import type { DocumentNode } from 'graphql';
import { finalize } from 'rxjs';
import { mutateDeleteByKeys } from '../../../modules/graphql/fetchers/mutate-delete-by-keys';

export function useGraphqlDeleteByKeys(mutation: DocumentNode) {
  const injector = inject(Injector);
  const loading = signal(false);

  function deleteByKeys(keys: Record<string, unknown>, headers?: Record<string, string>) {
    loading.set(true);
    return runInInjectionContext(injector, () => mutateDeleteByKeys(mutation, keys, headers)).pipe(
      finalize(() => loading.set(false)),
    );
  }

  return {
    deleteByKeys,
    loading: loading.asReadonly(),
  };
}
