// imports

import { useQuery } from "@tanstack/vue-query";
import { API_ENDPOINTS, QUERY_KEYS } from "~/constants";
import sanitizeHtml from 'sanitize-html';

// types

export type GetProductResponse = Product;

const useGetProduct = (id: string | number | undefined) => {

    // state

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

    // methods

    const handleGetProduct = async (id: string | number | undefined) => {
        const { data } = await axios.get<GetProductResponse>(`${API_ENDPOINTS.product.get}/${id}/`);
        return data;
    };

    return useQuery({
        queryKey: [QUERY_KEYS.product, id],
        queryFn: () => handleGetProduct(id),
        select: (product) => {
            const copyOfProduct = { ...product };

            copyOfProduct.description = sanitizeHtml(copyOfProduct.description);

            copyOfProduct.variants = copyOfProduct.variants.sort((a, b) => b.in_stock - a.in_stock);

            return copyOfProduct;
        }
    });
};

export default useGetProduct;
