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

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

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

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