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

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

  function deleteRows(
    query: Record<string, unknown>,
    constraint?: Record<string, unknown>,
    headers?: Record<string, string>,
  ) {
    loading.set(true);
    return runInInjectionContext(injector, () =>
      mutateDelete(mutation, query, constraint, headers),
    ).pipe(finalize(() => loading.set(false)));
  }

  return {
    delete: deleteRows,
    loading: loading.asReadonly(),
  };
}
