import type { ApiResponse, Branch } from "~/types/Contact";
import { computed, watch } from "vue";

export function useBranches() {
  const { locale } = useI18n();
  const config = useRuntimeConfig();
  const { data: country } = useUserCountry();

  const key = computed(
    () => `branches-${locale.value}-${country.value?.iso ?? "default"}`,
  );

  const { data, pending, refresh, error } = useAsyncData<ApiResponse<Branch[]>>(
    () => key.value,
    () =>
      $fetch(`${config.public.apiBase}branches`, {
        headers: {
          "Content-Language": locale.value,
        },
        params: {
          country: country.value?.iso,
        },
      }),
    {
      lazy: true,
      immediate: false,
    },
  );

  const branches = computed<Branch[]>(() => data.value?.data ?? []);
  const isLoading = computed(() => Boolean(pending.value));
  const isError = computed(() => Boolean(error.value));
  const isEmpty = computed(
    () => !isLoading.value && branches.value.length === 0,
  );

  watch(
    () => country.value?.iso,
    (iso) => {
      if (iso) refresh();
    },
    { immediate: true },
  );

  return {
    branches,
    refresh,
    isLoading,
    isError,
    error,
    isEmpty,
  };
}
