import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  approveQuotation,
  convertEnquiryToQuotation,
  createCustomer,
  createQuotationRevision,
  markQuotationStatus,
  rejectQuotation,
  revokeContactShare,
  shareContact,
  submitQuotationApproval,
  updateCustomer
} from './service';
import { crmKeys } from './queries';
import type {
  ApprovalActionPayload,
  ContactSharePayload,
  CustomerMutationPayload,
  Quotation
} from './types';

function invalidateCrm() {
  return getQueryClient().invalidateQueries({ queryKey: crmKeys.all });
}

export const createCustomerMutation = mutationOptions({
  mutationFn: (payload: CustomerMutationPayload) => createCustomer(payload),
  onSuccess: invalidateCrm
});

export const updateCustomerMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: string; values: CustomerMutationPayload }) =>
    updateCustomer(id, values),
  onSuccess: invalidateCrm
});

export const convertEnquiryMutation = mutationOptions({
  mutationFn: (enquiryId: string) => convertEnquiryToQuotation(enquiryId),
  onSuccess: invalidateCrm
});

export const submitApprovalMutation = mutationOptions({
  mutationFn: (quotationId: string) => submitQuotationApproval(quotationId),
  onSuccess: invalidateCrm
});

export const approveQuotationMutation = mutationOptions({
  mutationFn: (payload: ApprovalActionPayload) => approveQuotation(payload),
  onSuccess: invalidateCrm
});

export const rejectQuotationMutation = mutationOptions({
  mutationFn: (payload: ApprovalActionPayload) => rejectQuotation(payload),
  onSuccess: invalidateCrm
});

export const createQuotationRevisionMutation = mutationOptions({
  mutationFn: (quotationId: string) => createQuotationRevision(quotationId),
  onSuccess: invalidateCrm
});

export const markQuotationStatusMutation = mutationOptions({
  mutationFn: ({ quotationId, status }: { quotationId: string; status: Quotation['status'] }) =>
    markQuotationStatus(quotationId, status),
  onSuccess: invalidateCrm
});

export const shareContactMutation = mutationOptions({
  mutationFn: (payload: ContactSharePayload) => shareContact(payload),
  onSuccess: invalidateCrm
});

export const revokeContactShareMutation = mutationOptions({
  mutationFn: ({ contactId, shareId }: { contactId: string; shareId: string }) =>
    revokeContactShare(contactId, shareId),
  onSuccess: invalidateCrm
});
