
export const useFiles = () => {
    const toast = useToast()

    const auth = useAuthStore()

    let bucket = "filesdev"

    const uploadFiles = async (fileData, files,tags, upsert) => {
        const uploadSingleFile = async (file) => {
            //Create File Entry to Get ID for Folder

            const formData = new FormData()

            formData.append("file", file)
            formData.append("meta", JSON.stringify(fileData))

            const {fileReturn} = await useNuxtApp().$api("/api/files/upload",{
                method: "POST",
                body: formData
            })
        }

        if(files.length === 1) {
            await uploadSingleFile(files[0])
        } else if( files.length > 1) {

            for(let i = 0; i < files.length; i++){
                await uploadSingleFile(files[i])
            }

        }
    }

    const selectDocuments = async (sortColumn = null, folder = null) => {
        let data = []
        data = await useEntities("files").select("*, incominginvoice(*), project(*), vendor(*), customer(*), contract(*), plant(*), createddocument(*), vehicle(*), product(*), profile(*), check(*), inventoryitem(*)")

        if (!Array.isArray(data) || data.length === 0) {
            return []
        }


        const res =  await useNuxtApp().$api("/api/files/presigned",{
            method: "POST",
            body: {
                ids: data.map(i => i.id)
            }
        })

        const fileDataById = new Map(data.map((file) => [file.id, file]))

        return (res.files || []).map((file) => ({
            ...file,
            ...(fileDataById.get(file.id) || {}),
            url: file.url
        }))
    }

    const selectSomeDocuments = async (documentIds, sortColumn = null, folder = null) => {

        if(documentIds.length === 0) return []
        const res =  await useNuxtApp().$api("/api/files/presigned",{
            method: "POST",
            body: {
                ids: documentIds
            }
        })

        console.log(res)

        return res.files


    }

    const selectDocument = async (id) => {
        let documentIds = [id]
        if(documentIds.length === 0) return []
        const fileData = await useEntities("files").selectSingle(id)
        const res =  await useNuxtApp().$api("/api/files/presigned",{
            method: "POST",
            body: {
                ids: documentIds
            }
        })

        const file = res.files?.[0] || null
        return file ? {...file, ...(fileData || {}), url: file.url} : null
    }

    const downloadFile = async (id?: string, ids?: string[], returnAsBlob: Boolean = false) => {
        const url = id ? `/api/files/download/${id}` : `/api/files/download`
        const body = ids ? { ids } : undefined

        const res:any = await useNuxtApp().$api.raw(url, {
            method: "POST",
            body,
            responseType: "blob", // wichtig!
        })

        // Dateiname bestimmen
        let filename = "download"

        if (id) {
            // Einzeldatei → nimm den letzten Teil des Pfads aus Content-Disposition
            const contentDisposition = res.headers?.get("content-disposition")
            if (contentDisposition) {
                const match = contentDisposition.match(/filename="?([^"]+)"?/)
                if (match) filename = match[1]
            }
        } else {
            filename = "dateien.zip"
        }

        // Direkt speichern
        const blob = res._data as Blob

        if(returnAsBlob) {
            return blob
        } else {
            const link = document.createElement("a")
            link.href = URL.createObjectURL(blob)
            link.download = filename
            link.click()
            URL.revokeObjectURL(link.href)
        }



    }

    const dataURLtoFile = (dataurl:string, filename:string) => {
        let arr = dataurl.split(","),
            //@ts-ignore
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[arr.length - 1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type: mime});
    }


    return {uploadFiles, selectDocuments, selectSomeDocuments, selectDocument, downloadFile, dataURLtoFile}
}
