import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { assignLead, createLead, createLeadFollowup, deleteLead, updateLead } from './service';
import { leadKeys } from './queries';
import type { CreateLeadFollowupInput, CreateLeadInput, UpdateLeadInput } from './types';

async function invalidateLeadLists() {
  await getQueryClient().invalidateQueries({ queryKey: leadKeys.lists() });
}

async function invalidateLeadDetail(id: string) {
  await getQueryClient().invalidateQueries({ queryKey: leadKeys.detail(id) });
}

export async function invalidateLeadMutationQueries(id: string) {
  await Promise.all([invalidateLeadLists(), invalidateLeadDetail(id)]);
}

export const createLeadMutation = mutationOptions({
  mutationFn: (values: CreateLeadInput) => createLead(values),
  onSettled: async (data, error) => {
    if (!error && data?.lead?.id) {
      await invalidateLeadMutationQueries(data.lead.id);
      return;
    }

    if (!error) {
      await invalidateLeadLists();
    }
  }
});

export const updateLeadMutation = mutationOptions({
  mutationFn: ({ id, values }: { id: string; values: UpdateLeadInput }) => updateLead(id, values),
  onSettled: async (_data, error, variables) => {
    if (!error) {
      await invalidateLeadMutationQueries(variables.id);
    }
  }
});

export const deleteLeadMutation = mutationOptions({
  mutationFn: ({ id }: { id: string }) => deleteLead(id),
  onSettled: async (_data, error, variables) => {
    if (!error) {
      await invalidateLeadLists();
      getQueryClient().removeQueries({ queryKey: leadKeys.detail(variables.id) });
    }
  }
});

export const createLeadFollowupMutation = mutationOptions({
  mutationFn: ({ leadId, values }: { leadId: string; values: CreateLeadFollowupInput }) =>
    createLeadFollowup(leadId, values),
  onSettled: async (_data, error, variables) => {
    if (!error) {
      await invalidateLeadDetail(variables.leadId);
    }
  }
});

export const assignLeadMutation = mutationOptions({
  mutationFn: ({
    leadId,
    values
  }: {
    leadId: string;
    values: { salesOwnerId: string; assignmentRemark?: string | null };
  }) => assignLead(leadId, values),
  onSettled: async (_data, error, variables) => {
    if (!error) {
      await invalidateLeadMutationQueries(variables.leadId);
    }
  }
});
