import { nextTick, onMounted, ref, watch, type Ref } from "vue";
import { useRoute } from "vue-router";

export function useLoadQuerys<T extends Record<string, any>>(
  defaults: T, 
  afterLoad?: (querys: T) => void
) {

  const querys = ref<T>(defaults) as Ref<T>; 
  const route = useRoute();

  function loadQuerys() {
    const _querys = route.query;
    if (_querys) {
      for (const key in querys.value) {
        if (typeof defaults[key] === 'number')
          (querys.value as Record<string, any>)[key] = Number(_querys[key]); 
        else
          querys.value[key] = _querys[key] as any;
      }
    }
    afterLoad?.(querys.value);
  }

  watch(route, () => {
    loadQuerys();
  });

  onMounted(() => {
    nextTick(() => {
      loadQuerys();
    });
  });

  return {
    querys,
  }
}