<template>
    <a :href="href" @click="downloadFile" target="_blank">
        <slot></slot>
    </a>
  </template>
<script>
    export default {
        props: {
            href: {
                type: String,
                required: true,
            },
        },
        methods: {
            downloadFile(event) {
                event.preventDefault();

                fetch(this.href, {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + this.$store.getters.getAccessToken,
                    },
                })
                .then((response) => {
                    if (response.status === 200) {
                        const contentDisposition = response.headers.get('Content-Disposition');
                        const filename = contentDisposition ? contentDisposition.split('filename=')[1] : 'downloaded_file';

                        return response.blob()
                        .then((blob) => {
                            const blobUrl = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = blobUrl;
                            a.download = filename;
                            a.style.display = 'none';
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            window.URL.revokeObjectURL(blobUrl);
                        });
                    } else {
                        console.error('Request failed with status:', response.status);
                    }
                })
                .catch((error) => {
                    console.error('Network error:', error);
                });
            }
        }
    }
</script>
