import { computed } from '@angular/core';
import type { DocumentNode } from 'graphql';
import { useGraphqlCreate } from '../atoms/graphql/use-graphql-create';
import { useGraphqlFindById } from '../atoms/graphql/use-graphql-find-by-id';
import { useGraphqlUpdate } from '../atoms/graphql/use-graphql-update';

interface GraphqlDetailConfig {
  readonly queryObject: DocumentNode;
  readonly objectKey: string;
  readonly mutationCreateObject: DocumentNode;
  readonly mutationUpdateObject: DocumentNode;
  readonly fields?: string;
}

export function useGraphqlDetail<T>(config: GraphqlDetailConfig) {
  const findByIdComposable = useGraphqlFindById<T>(
    config.queryObject,
    config.objectKey,
    config.fields,
  );
  const createComposable = useGraphqlCreate(config.mutationCreateObject);
  const updateComposable = useGraphqlUpdate(config.mutationUpdateObject);

  const loading = computed(
    () => findByIdComposable.loading() || createComposable.loading() || updateComposable.loading(),
  );

  return {
    findById: findByIdComposable.findById,
    item: findByIdComposable.item,
    create: createComposable.create,
    // Enriched payload from last create call (includes generated UUID).
    lastPayload: createComposable.lastPayload,
    update: updateComposable.update,
    loading,
  };
}

export type GraphqlDetail<T> = ReturnType<typeof useGraphqlDetail<T>>;
