import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  createMasterOption,
  deleteMasterOption,
  updateMasterOption
} from './service';
import { masterOptionKeys } from './queries';
import type { MasterOptionMutationPayload } from './types';

async function invalidateMasterOptionLists() {
  const queryClient = getQueryClient();
  await Promise.all([
    queryClient.invalidateQueries({ queryKey: masterOptionKeys.lists() }),
    queryClient.invalidateQueries({ queryKey: masterOptionKeys.categories() })
  ]);
}

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

export const createMasterOptionMutation = mutationOptions({
  mutationFn: (data: MasterOptionMutationPayload) => createMasterOption(data),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateMasterOptionLists();
    }
  }
});

export const updateMasterOptionMutation = mutationOptions({
  mutationFn: ({
    id,
    values
  }: {
    id: string;
    values: Partial<MasterOptionMutationPayload>;
  }) => updateMasterOption(id, values),
  onSettled: async (_data, error, variables) => {
    if (!error) {
      await Promise.all([
        invalidateMasterOptionLists(),
        invalidateMasterOptionDetail(variables.id)
      ]);
    }
  }
});

export const deleteMasterOptionMutation = mutationOptions({
  mutationFn: (id: string) => deleteMasterOption(id),
  onSettled: async (_data, error, id) => {
    if (!error) {
      const queryClient = getQueryClient();
      await invalidateMasterOptionLists();
      queryClient.removeQueries({ queryKey: masterOptionKeys.detail(id) });
    }
  }
});
