import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { invalidateContentWorkflowData } from '@/lib/query-invalidation';
import {
  createAnnouncement,
  deleteAnnouncement,
  pinAnnouncement,
  unpinAnnouncement,
  updateAnnouncement,
  updateAnnouncementState
} from './service';
import { announcementKeys } from './queries';
import type { AnnouncementMutationPayload, AnnouncementWorkflowActionPayload } from './types';

export const createAnnouncementMutation = mutationOptions({
  mutationFn: (data: AnnouncementMutationPayload) => createAnnouncement(data),
  onSuccess: () => {
    return invalidateContentWorkflowData();
  }
});

export const updateAnnouncementMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: number; values: AnnouncementMutationPayload }) =>
    updateAnnouncement(id, values),
  onSuccess: (_data, variables) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateContentWorkflowData(queryClient),
      queryClient.invalidateQueries({ queryKey: announcementKeys.detail(variables.id) })
    ]);
  }
});

export const updateAnnouncementStateMutation = mutationOptions({
  mutationFn: ({
    id,
    values
  }: {
    id: number;
    values: AnnouncementWorkflowActionPayload;
  }) => updateAnnouncementState(id, values),
  onSuccess: (_data, variables) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateContentWorkflowData(queryClient),
      queryClient.invalidateQueries({ queryKey: announcementKeys.detail(variables.id) })
    ]);
  }
});

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

export const pinAnnouncementMutation = mutationOptions({
  mutationFn: (id: number) => pinAnnouncement(id),
  onSuccess: (_data, id) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateContentWorkflowData(queryClient),
      queryClient.invalidateQueries({ queryKey: announcementKeys.detail(id) })
    ]);
  }
});

export const unpinAnnouncementMutation = mutationOptions({
  mutationFn: (id: number) => unpinAnnouncement(id),
  onSuccess: (_data, id) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateContentWorkflowData(queryClient),
      queryClient.invalidateQueries({ queryKey: announcementKeys.detail(id) })
    ]);
  }
});
