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

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

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

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