import { useQueryClient } from '@tanstack/vue-query';
import { isArray } from 'lodash';
import { api } from 'src/boot/axios';
import { notifyError, notifySuccess } from 'src/helpers';
import { Ref } from 'vue';
import { CollectionLabel, collectionsTextsMap } from './models';
import { useRequestConfirmation } from './useRequestConfirmation';

type QueryKey = string | number | null;
export function useDelete(url: string, queryKeys: (QueryKey | QueryKey[])[] = [], item: CollectionLabel) {
  const queryClient = useQueryClient();
  const { requestConfirmation } = useRequestConfirmation();
  const [gender, singular] = collectionsTextsMap[item];
  const vocal = gender === 'f' ? 'a' : 'e';
  const art = gender === 'f' ? 'la' : 'el';
  const deleteItem = async (id: number | string, loading?: Ref<boolean>, loadingId?: Ref<number | string | null>, message?: string) => {
    return new Promise((resolve, reject) => {
      requestConfirmation({
        title: `Eliminar ${singular}`,
        message: message || `¿Estás seguro que quieres eliminar est${vocal} ${singular}?`,
        action: () => {
          loading ? (loading.value = true) : '';
          loadingId ? (loadingId.value = id) : '';
          api
            .delete([url, id].join('/'))
            .then(() => {
              notifySuccess(`${singular} eliminad${vocal} correctamente`);
              queryKeys?.forEach((key) => {
                queryClient.invalidateQueries({ queryKey: isArray(key) ? key : [key], exact: false, refetchType: 'all' })
              })
              resolve(true);
            })
            .catch((error) => {
              notifyError(error, `Hubo un error eliminando ${art} ${singular}`);
              reject(error);
            })
            .finally(() => {
              loading ? (loading.value = false) : ''
              loadingId ? (loadingId.value = null) : ''
            })

        },
      });
    });
  };

  return deleteItem;
}
