import {defineStore} from "pinia";
import {ref} from "vue";
import type {IProduct} from "@/types/product-d-t";
import {useProductFilterStore} from "@/pinia/useProductFilterStore";
import {convertProductResponse} from "@/plugins/data/product-data";
import type {IFetchProductOptions, TProductDataWithPagination} from "@/types/fetch-product-options-d-t";
import type {IProductResponse} from "@/types/product-response-d-t";
import type {IMeta} from "@/types/meta-d-t";

export const useSearchStore = defineStore("search", () => {
    // const route = useRoute();
    const router = useRouter();
    const loading = ref<boolean>(false);
    const products = ref<IProduct[]>([]);
    const store = useProductFilterStore();
    const meta = ref<IMeta>(store.product_meta);

    const {$settings}: any = useNuxtApp();
    const noImageUrl = $settings?.noImageUrl;

    const triggerSearch = (page?: number) => {
        page = page || Number(router.currentRoute.value?.query?.page || 1);
        loading.value = true;
        let searchText = String(router.currentRoute.value?.query?.searchText || '')
        let opt: IFetchProductOptions = {
            search: searchText,
            page,
            plain: true,
            pagination: true,
        };

        store.updateProductOptions(opt);
        return (
            searchText ?
                // @ts-ignore
                store.loadProducts(opt) :
                Promise.resolve([])
        )
            // @ts-ignore
            .then(({data, meta: $meta}: TProductDataWithPagination<IProduct[] | IProductResponse[]>) => {
                meta.value = $meta;
                data = data.map((x: IProductResponse) => convertProductResponse(x, noImageUrl));

                let _data: Number[] = [];
                return data.filter((x: IProduct) => {
                    if (_data.includes(Number(x.id))) {
                        return false
                    }
                    _data.push(Number(x.id));
                    return true;
                })
            })
            .then((products: IProduct[]) => {
                if (process.client) {
                    if (products.length === 0 && Number(opt?.page) > 1) {
                        router.push({
                            query: {
                                ...router.currentRoute.value?.query,
                                page: 1,
                                l: 258
                            }
                        })

                        return products;
                    }

                    let $products = store.filterProducts(products || [])
                    handlePagination(
                        $products,
                        0,
                        $products.length
                    )
                }

                return products;
            })
            .then(data => {
                scrollToTop();
                // @ts-ignore
                products.value = (data?.value || []).map(x => convertProductResponse(x));

                // @ts-ignore
                store.setData(products.value)

                loading.value = false
                return products.value || products;
            })
    };

    return {
        loading,
        products,
        meta,
        triggerSearch,
    }
});
