import { formatContactName, Id } from '@win2win/shared';
import { useFetch } from '@win2win/shared-ui';
import { ContactoLite } from 'src/models';
import { computed, Ref } from 'vue';

export function useContactosCaptacionOptions(idCaptacion: Ref<Id | null | undefined>, roles?: string[]) {
  if (!idCaptacion.value) {
    return {
      data: computed(() => []),
      fetching: false,
    };
  }
  const key = computed(() => ['captacion', idCaptacion.value || null, 'contactos_options', { roles }]);
  const query = computed(() => `w2w-query/contactos(id_captacion=${idCaptacion.value})`);
  const { data, fetching } = useFetch<ContactoLite[]>(
    key,
    query,
    {
      contactos: ['id', 'nombre', 'apellido', 'apellido2', 'roles'],
    },
    (data) => (data || []).filter((c: ContactoLite) => (roles ? roles.some((r) => c.roles?.includes(r)) : true))
  );

  type Contact = Parameters<typeof formatContactName>[0];
  const options = computed(() => data.value?.map((contact) => ({ label: formatContactName(contact as Contact), value: contact.id, data: contact })) || []);

  return {
    data: options,
    fetching,
  };
}
