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

export const useTopicStore = defineStore('topic', () => {
    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 fetchById(topicId: string) {
        const { data, error } =  await useFetch<any>(`/api/services/topic`, {
            query: {
                topicId: topicId
            }
        })
        if(error.value) {
            return null
        }

        return data.value
    }

    async function fetchByCategoryId(categoryId: number, limit?: number) {
        if(limit) {
            pagination.value.limit = limit
        }
        const { data, error } =  await useFetch<any>(`/api/services/topics-paging`, {
            query: {
                categoryId: categoryId,
                limit: pagination.value.limit,
                page: pagination.value.page,
                sort: 'createdon desc'
            }
        })
        if(error.value) {
            return null
        }

        return data.value.items
    }

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

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