import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  createEmailConfiguration,
  deleteEmailConfiguration,
  sendEmailConfigurationTestEmail,
  testEmailConfigurationConnection,
  updateEmailConfiguration,
} from './service';
import { emailConfigurationKeys } from './queries';
import type { EmailConfigurationPayload, SendTestEmailPayload } from './types';

function invalidateEmailConfigurations() {
  getQueryClient().invalidateQueries({ queryKey: emailConfigurationKeys.all });
}

export const createEmailConfigurationMutation = mutationOptions({
  mutationFn: (payload: EmailConfigurationPayload) => createEmailConfiguration(payload),
  onSuccess: invalidateEmailConfigurations,
});

export const updateEmailConfigurationMutation = mutationOptions({
  mutationFn: ({ id, payload }: { id: string; payload: EmailConfigurationPayload }) =>
    updateEmailConfiguration(id, payload),
  onSuccess: invalidateEmailConfigurations,
});

export const deleteEmailConfigurationMutation = mutationOptions({
  mutationFn: (id: string) => deleteEmailConfiguration(id),
  onSuccess: invalidateEmailConfigurations,
});

export const testEmailConfigurationConnectionMutation = mutationOptions({
  mutationFn: (id: string) => testEmailConfigurationConnection(id),
  onSuccess: invalidateEmailConfigurations,
});

export const sendEmailConfigurationTestEmailMutation = mutationOptions({
  mutationFn: ({
    id,
    payload,
  }: {
    id: string;
    payload: SendTestEmailPayload;
  }) => sendEmailConfigurationTestEmail(id, payload),
  onSuccess: invalidateEmailConfigurations,
});
