import { ref } from "vue"

export function useAjax() {
    const loading = ref(false)
    const error = ref(null)
    const data = ref(null)
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

    async function request(url, options = {}) {
        loading.value = true
        const isFormData = options.body instanceof FormData

        error.value = null
        data.value = null

        try {
            const response = await fetch(url, {
                method: options.method || "GET",
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
                    ...(options.headers || {}),
                },
                body: isFormData
                    ? options.body          // ✅ FormData direkt
                    : options.body
                        ? JSON.stringify(options.body)
                        : null,
            })

            if (!response.ok) throw new Error(`HTTP ${response.status}`)

            const result = await response.json()
            data.value = result
            return result
        } catch (err) {
            error.value = err
            console.error("AJAX Error:", err)
            return null
        } finally {
            loading.value = false
        }
    }


    async function download(url, options = {}) {
        loading.value = true
        error.value = null

        try {
            const response = await fetch(url, {
                method: options.method || "GET",
                headers: {
                    ...(options.headers || {}),
                },
                body: options.body ? JSON.stringify(options.body) : null,
            })

            if (!response.ok) throw new Error(`HTTP ${response.status}`)

            const blob = await response.blob()
            const filename =
                options.filename ||
                response.headers
                    .get("Content-Disposition")
                    ?.split("filename=")[1]
                    ?.replace(/["']/g, "") ||
                "download.bin"

            const downloadUrl = window.URL.createObjectURL(blob)
            const a = document.createElement("a")
            a.href = downloadUrl
            a.download = filename
            document.body.appendChild(a)
            a.click()
            a.remove()
            window.URL.revokeObjectURL(downloadUrl)

            return true
        } catch (err) {
            error.value = err
            console.error("Download Error:", err)
            return false
        } finally {
            loading.value = false
        }
    }

    return {data, loading, error, request, download}
}
