import { useFetch } from '@win2win/shared-ui';
import { compact, snakeCase } from 'lodash';
import { Ref, ref } from 'vue';

export function useSimpleQuery<T = any>(query: string, fields?: string[] | null, mapper: (v) => any = (v) => v, enabled?: Ref<boolean>) {
  // esto es para que, si se pasa un id, se busque por id y se separe de la colección. Asi el queryKey es más limpio
  const regex = /\(([^)]+)\)/;
  let collection = '';
  let condition: string | null = null;
  const matches = query.match(regex);
  if (matches) {
    collection = query.replace(matches[0], '');
    condition = matches[0].slice(1, -1);
  } else {
    collection = query;
  }

  const rawCollection = snakeCase(collection);
  const queryKey = compact(['simple-query', rawCollection, condition, (fields || []).join(',')]);
  const { data, fetching } = useFetch<T>(
    ref(queryKey),
    ref('w2w-query/' + rawCollection + (condition ? `(${condition})` : '')),
    fields
      ? {
          [rawCollection]: fields,
        }
      : {},
    mapper,
    { enabled: enabled || ref(true) }
  );

  return {
    data,
    fetching,
    queryKey,
  };
}
