export default function useAddress() {
  function add({
    type = "",
    user = "",
    org = "",
    country = "",
    countryCode = "",
    phoneNumber = "",
    address = "",
    continuedAddress = "",
    city = "",
    province = "",
    postalCode = "",
    taxId = "",
  } = {}) {
    return useNuxtApp().$api("/api/addresses", {
      method: "POST",
      body: {
        type,
        user,
        org,
        country,
        countryCode,
        phoneNumber,
        address,
        continuedAddress,
        city,
        province,
        postalCode,
        taxId,
      },
    });
  }

  function getByUserId(user = "") {
    return useNuxtApp().$api<TAddress>(`/api/addresses/user/${user}`);
  }

  const _address = useState("address", (): TAddress => {
    return {
      type: "",
      user: "",
      org: "",
      country: "",
      address: "",
      continuedAddress: "",
      city: "",
      province: "",
      postalCode: "",
      taxId: "",
    };
  });

  function reset() {
    _address.value.type = "";
    _address.value.user = "";
    _address.value.org = "";
    _address.value.country = "";
    _address.value.address = "";
    _address.value.continuedAddress = "";
    _address.value.city = "";
    _address.value.province = "";
    _address.value.postalCode = "";
    _address.value.taxId = "";
  }

  function set({
    type = "",
    user = "",
    org = "",
    country = "",
    address = "",
    continuedAddress = "",
    city = "",
    province = "",
    postalCode = "",
    taxId = "",
  } = {}) {
    _address.value.type = type;
    _address.value.user = user;
    _address.value.org = org;
    _address.value.country = country;
    _address.value.address = address;
    _address.value.continuedAddress = continuedAddress;
    _address.value.city = city;
    _address.value.province = province;
    _address.value.postalCode = postalCode;
    _address.value.taxId = taxId;
  }

  const { address, city, province, postalCode, country } = _address.value;

  const completeAddress = computed(() => {
    return `${address ? `${address}, ` : ""}${
      city ? `${city}, ` : ""
    } ${province} ${postalCode ? `${postalCode}, ` : ""} ${country}`;
  });

  return {
    add,
    reset,
    set,
    getByUserId,
    address: _address,
    completeAddress,
  };
}
