import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  createApprovalEscalationPolicy,
  createApprovalReminderPolicy,
  deleteApprovalEscalationPolicy,
  deleteApprovalReminderPolicy,
  runApprovalAutomation,
  updateApprovalEscalationPolicy,
  updateApprovalReminderPolicy
} from './service';
import { approvalAutomationKeys } from './queries';
import type { EscalationPolicyPayload, ReminderPolicyPayload } from './types';

async function invalidateAutomationQueries() {
  const queryClient = getQueryClient();
  await Promise.all([
    queryClient.invalidateQueries({ queryKey: approvalAutomationKeys.pendingQueue() }),
    queryClient.invalidateQueries({ queryKey: approvalAutomationKeys.reminderPolicies() }),
    queryClient.invalidateQueries({ queryKey: approvalAutomationKeys.escalationPolicies() })
  ]);
}

export const runApprovalAutomationMutation = mutationOptions({
  mutationFn: () => runApprovalAutomation(),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateAutomationQueries();
    }
  }
});

export const createApprovalReminderPolicyMutation = mutationOptions({
  mutationFn: (data: ReminderPolicyPayload) => createApprovalReminderPolicy(data),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateAutomationQueries();
    }
  }
});

export const updateApprovalReminderPolicyMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: string; values: ReminderPolicyPayload }) =>
    updateApprovalReminderPolicy(id, values),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateAutomationQueries();
    }
  }
});

export const deleteApprovalReminderPolicyMutation = mutationOptions({
  mutationFn: (id: string) => deleteApprovalReminderPolicy(id),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateAutomationQueries();
    }
  }
});

export const createApprovalEscalationPolicyMutation = mutationOptions({
  mutationFn: (data: EscalationPolicyPayload) => createApprovalEscalationPolicy(data),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateAutomationQueries();
    }
  }
});

export const updateApprovalEscalationPolicyMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: string; values: EscalationPolicyPayload }) =>
    updateApprovalEscalationPolicy(id, values),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateAutomationQueries();
    }
  }
});

export const deleteApprovalEscalationPolicyMutation = mutationOptions({
  mutationFn: (id: string) => deleteApprovalEscalationPolicy(id),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateAutomationQueries();
    }
  }
});
