// imports

import { API_ENDPOINTS } from "~/constants";
import { useQuery } from "@tanstack/vue-query";

const useDownloadInvoice = (transactionId: string) => {
    // state

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

    const enabled = ref(false);

    // methods

    const download = () => {
        if (!enabled.value) enabled.value = true;
        queryClient.invalidateQueries({
            queryKey: ["download-invoice", transactionId],
        });
    };

    // query

    const handleDownloadInvoice = async () => {
        const { data } = await axios.get<Blob>(`${API_ENDPOINTS.orders.cart.download_invoice}/${transactionId}`, {
            responseType: "blob",
        });
        return data;
    };

    const { data: file, isLoading } = useQuery({
        queryKey: ["download-invoice", transactionId],
        queryFn: () => handleDownloadInvoice(),
        enabled,
        refetchOnWindowFocus: false,
    });

    // watch

    whenever(file, () => {
        if (!!file.value) {
            const url = URL.createObjectURL(file.value);
            const link = document.createElement("a");
            link.href = url;
            link.download = "invoice.pdf";
            link.click();
            URL.revokeObjectURL(url);

            enabled.value = false;
        }
    });

    return {
        downloadIsLoading: isLoading,
        downloadFn: download,
    };
};

export default useDownloadInvoice;
