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

export function useGraphqlCreate(mutation: DocumentNode) {
  const injector = inject(Injector);
  const loading = signal(false);
  const lastPayload = signal<Record<string, unknown> | null>(null);

  function create(payload: Record<string, unknown>, headers?: Record<string, string>) {
    if ('id' in payload && !payload['id']) {
      payload = { ...payload, id: crypto.randomUUID() };
    }
    lastPayload.set(payload);
    loading.set(true);
    return runInInjectionContext(injector, () => mutateCreate(mutation, payload, headers)).pipe(
      finalize(() => loading.set(false)),
    );
  }

  return {
    create,
    loading: loading.asReadonly(),
    lastPayload: lastPayload.asReadonly(),
  };
}
