import { itGetCached } from "@/fetchHelpers";
import { useUserStore } from "@/stores/user";
import { isString, startsWith } from "lodash";
import type { Ref } from "vue";
import { computed, ref } from "vue";

export function profileNextRoute(courseType: string | string[]) {
  if (courseType === "uk") {
    return "setupComplete";
  }
  // vv- -> vv-de, vv-fr or vv-it
  if (isString(courseType) && startsWith(courseType, "vv-")) {
    return "checkoutAddress";
  }
  return "";
}

export type Organisation = {
  organisation_id: number;
  name_de: string;
  name_fr: string;
  name_it: string;
};

export type Country = {
  country_id: number;
  name_de: string;
  name_fr: string;
  name_it: string;
};

export type Entities = {
  organisations: Organisation[];
  countries: Country[];
};

export function useEntities() {
  const user = useUserStore();
  const entities: Ref<Entities | undefined> = ref();

  itGetCached("/api/core/entities/").then((res) => {
    entities.value = res;
  });

  const organisations = computed(() => {
    if (entities.value) {
      return entities.value.organisations.map((c) => ({
        id: c.organisation_id,
        name: c[`name_${user.language}`],
      }));
    }
    return [];
  });

  const countries = computed(() => {
    if (entities.value) {
      return entities.value.countries.map((c) => ({
        id: c.country_id,
        name: c[`name_${user.language}`],
      }));
    }
    return [];
  });

  return { organisations, countries };
}
