import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { invalidateContentWorkflowData } from '@/lib/query-invalidation';
import {
  createOnlineLesson,
  deleteOnlineLesson,
  updateOnlineLesson,
  updateOnlineLessonState
} from './service';
import { onlineLessonKeys } from './queries';
import type { OnlineLessonMutationPayload, OnlineLessonWorkflowActionPayload } from './types';

export const createOnlineLessonMutation = mutationOptions({
  mutationFn: (data: OnlineLessonMutationPayload) => createOnlineLesson(data),
  onSuccess: () => {
    return invalidateContentWorkflowData();
  }
});

export const updateOnlineLessonMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: number; values: OnlineLessonMutationPayload }) =>
    updateOnlineLesson(id, values),
  onSuccess: (_data, variables) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateContentWorkflowData(queryClient),
      queryClient.invalidateQueries({ queryKey: onlineLessonKeys.detail(variables.id) })
    ]);
  }
});

export const updateOnlineLessonStateMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: number; values: OnlineLessonWorkflowActionPayload }) =>
    updateOnlineLessonState(id, values),
  onSuccess: (_data, variables) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateContentWorkflowData(queryClient),
      queryClient.invalidateQueries({ queryKey: onlineLessonKeys.detail(variables.id) })
    ]);
  }
});

export const deleteOnlineLessonMutation = mutationOptions({
  mutationFn: (id: number) => deleteOnlineLesson(id),
  onSuccess: () => {
    return invalidateContentWorkflowData();
  }
});
