// imports

import { useQuery } from "@tanstack/vue-query";
import { useAppParams } from "~/composables/global/useAppParams";
import { API_ENDPOINTS, QUERY_KEYS } from "~/constants";

// types

export type GetProductsResponse = ApiPaginated<ProductListItem>;

// composable

const useGetProducts = () => {
    // state

    const { $axios: axios, $queryClient: queryClient } = useNuxtApp();

    const { search, sort, in_stock, has_discount, slug, price_gte, price_lte, page } = useAppParams();

    const searchDebounced = refDebounced(search, 500);

    // computed

    const products_category = computed(() => {
        if (Array.isArray(slug.value) && slug.value.length >= 2) {
            return slug.value[1];
        }
        return undefined;
    });

    const filters_clone = computed(() => {
        return {
            search,
            sort,
            in_stock,
            has_discount,
            price_gte,
            price_lte,
        };
    });

    // watch

    watch(
        () => filters_clone.value,
        () => {
            page.value = 1;
        },
        {
            deep: true,
        },
    );

    // methods

    const handleGetProducts = async ({ signal }: { signal: AbortSignal }) => {
        const { data } = await axios.get<GetProductsResponse>(`${API_ENDPOINTS.products.get_all}`, {
            params: {
                sort: sort.value || "newest",
                in_stock: in_stock.value,
                search: searchDebounced.value,
                has_discount: has_discount.value,
                category: products_category.value,
                price_gte: price_gte.value,
                price_lte: price_lte.value,
                offset: Number(page.value) * 15 - 15,
                limit: 15,
            },
            signal,
        });

        return data;
    };

    return useQuery({
        staleTime: 60 * 1000,
        queryKey: [
            QUERY_KEYS.products,
            searchDebounced,
            sort,
            in_stock,
            has_discount,
            products_category,
            price_gte,
            price_lte,
            page,
        ],
        queryFn: ({ signal }) => handleGetProducts({ signal }),
    });
};

export default useGetProducts;
