import { useFetch } from '@win2win/shared-ui';
import { computed, isRef, Ref, ref } from 'vue';

type Cliente = string | boolean;
type MaybeRef<T> = Ref<T> | T;

export function useSituaciones(cliente?: MaybeRef<Cliente>) {
  const _cliente = computed(() => (isRef(cliente) ? cliente.value : cliente));
  const codCliente = computed(() => {
    if (_cliente.value === undefined) return null;
    return typeof _cliente.value === 'number' ? _cliente.value : null;
  });
  const clientes = computed(() => !!_cliente.value);

  const queryKey = ref(['situaciones']);
  const path = ref('w2w-query/situaciones');
  const { data: _data, fetching } = useFetch<Situacion[]>(queryKey, path, {
    situaciones: ['id', 'id_empresa', 'nombre', 'descripcion', 'cod_cliente', 'clientes'],
  });

  const data = computed(
    () =>
      _data.value?.filter((s) => {
        if (codCliente.value) return s.cod_cliente === codCliente.value;
        if (clientes.value) return !!s.clientes;
        return !s.clientes;
      }) || []
  );

  return { data, fetching };
}

export interface Situacion {
  id: number;
  id_empresa: number;
  cod_cliente: number;
  nombre: string;
  descripcion: string;
  clientes: boolean | number;
}
