import { ref } from 'vue';
import { defineStore } from 'pinia';
import { api } from 'src/boot/axios';

export interface SubDistrict {
  updatedAt: string;
  updatedBy: string;
  createdAt: string;
  createdBy: string;
  districtId: string;
  zipCode: string;
  nameEN: string;
  name: string;
  id: string;
}

export interface District {
  updatedAt: string;
  updatedBy: string;
  createdAt: string;
  createdBy: string;
  provinceId: string;
  nameEN: string;
  name: string;
  id: string;
}

export interface Province {
  updatedAt: string;
  updatedBy: string;
  createdAt: string;
  createdBy: string;
  nameEN: string;
  name: string;
  id: string;
}

const useAddressStore = defineStore('api-address', () => {
  const province = ref<Province[]>();
  const district = ref<Record<Province['id'], District[]>>({});
  const subDistrict = ref<Record<District['id'], SubDistrict[]>>({});

  async function fetchProvince() {
    if (province.value) return province.value;

    const res = await api.get<Province[]>('/address/province');

    if (!res) return false;

    province.value = res.data;

    return province.value;
  }

  async function fetchDistrictByProvinceId(provinceId: string) {
    if (district.value[provinceId]) return district.value[provinceId];

    const res = await api.get<District[]>(
      `/address/province/${provinceId}/district`,
    );

    if (!res) return false;

    district.value[provinceId] = res.data;

    return district.value[provinceId];
  }

  async function fetchSubDistrictByProvinceId(districtId: string) {
    if (subDistrict.value[districtId]) return subDistrict.value[districtId];

    const res = await api.get<SubDistrict[]>(
      `/address/district/${districtId}/sub-district`,
    );

    if (!res) return false;

    subDistrict.value[districtId] = res.data;

    return subDistrict.value[districtId];
  }

  return {
    fetchProvince,
    fetchDistrictByProvinceId,
    fetchSubDistrictByProvinceId,
  };
});

export default useAddressStore;
