import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  createDocumentSequence,
  deleteDocumentSequence,
  resetDocumentSequence,
  updateDocumentSequence
} from './client-service';
import { documentSequenceKeys } from './queries';
import type { DocumentSequenceMutationPayload, DocumentSequenceResetPayload } from './types';

async function invalidateDocumentSequences() {
  await getQueryClient().invalidateQueries({ queryKey: documentSequenceKeys.lists() });
}

async function invalidateDocumentSequenceDetail(id: string) {
  await Promise.all([
    getQueryClient().invalidateQueries({ queryKey: documentSequenceKeys.detail(id) }),
    getQueryClient().invalidateQueries({ queryKey: documentSequenceKeys.preview(id) })
  ]);
}

export const createDocumentSequenceMutation = mutationOptions({
  mutationFn: (data: DocumentSequenceMutationPayload) => createDocumentSequence(data),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateDocumentSequences();
    }
  }
});

export const updateDocumentSequenceMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: string; values: Partial<DocumentSequenceMutationPayload> }) =>
    updateDocumentSequence(id, values),
  onSettled: async (_data, error, variables) => {
    if (!error) {
      await Promise.all([
        invalidateDocumentSequences(),
        invalidateDocumentSequenceDetail(variables.id)
      ]);
    }
  }
});

export const deleteDocumentSequenceMutation = mutationOptions({
  mutationFn: (id: string) => deleteDocumentSequence(id),
  onSettled: async (_data, error, id) => {
    if (!error) {
      const queryClient = getQueryClient();
      await invalidateDocumentSequences();
      queryClient.removeQueries({ queryKey: documentSequenceKeys.detail(id) });
      queryClient.removeQueries({ queryKey: documentSequenceKeys.preview(id) });
    }
  }
});

export const resetDocumentSequenceMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: string; values: DocumentSequenceResetPayload }) =>
    resetDocumentSequence(id, values),
  onSettled: async (_data, error, variables) => {
    if (!error) {
      await Promise.all([
        invalidateDocumentSequences(),
        invalidateDocumentSequenceDetail(variables.id)
      ]);
    }
  }
});
