import { LocationQuery } from "vue-router";
import { defineStore, acceptHMRUpdate } from "pinia";

export const useEventStore = defineStore('event', () => {

    const pagination = ref({
        page: utils.toNumber(useRuntimeConfig().public.pagingDefault),
        limit: utils.toNumber(useRuntimeConfig().public.pagingLimit),
        total: 0,
    });

    function setStateFromRoute(query: LocationQuery) {
        if (query.page) pagination.value.page = utils.toNumber(query.page)
        else pagination.value.page = utils.toNumber(useRuntimeConfig().public.pagingDefault);
        if (query.limit) pagination.value.limit = utils.toNumber(query.limit)
        else pagination.value.limit = utils.toNumber(useRuntimeConfig().public.pagingLimit);
    }

    async function listPaging(siteId: number, page: number, fetch: number) {
        const { data, error } = await useFetch<any>(`/api/services/events-paging?siteId=${siteId}&page=${page}&fetch=${fetch}`)
        if (error.value) {
            return null
        }
        return data.value
    }

    async function fetchById(id: string) {
        const { data, error } = await useFetch<any>(`/api/services/event`, {
            query: {
                eventId: id
            }
        })
        if(error.value) {
            return null
        }

        return data.value
    }

    return { listPaging, fetchById, setStateFromRoute, pagination }
})

if (import.meta.hot) {
    import.meta.hot.accept(acceptHMRUpdate(useEventStore, import.meta.hot))
}