import type { TaskDocument } from './dto/task-document'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'
import { $fetch } from 'ofetch'

export function useTaskDocumentService() {
    const api = useApi()
    const config = useRuntimeConfig()
    const baseURL = config.public.apiBase || '/api'

    async function getByTask(taskId: number): Promise<TaskDocument[]> {
        const data = await api.get<HydraCollection<TaskDocument>>('/task_documents', {
            task: `/api/tasks/${taskId}`,
        })
        return extractHydraMembers(data)
    }

    async function uploadWithRelation(relationField: string, relationIri: string, file: File): Promise<TaskDocument> {
        const formData = new FormData()
        formData.append('file', file)
        formData.append(relationField, relationIri)

        return $fetch<TaskDocument>(`${baseURL}/task_documents`, {
            method: 'POST',
            body: formData,
            credentials: 'include',
        })
    }

    async function upload(taskId: number, file: File): Promise<TaskDocument> {
        return uploadWithRelation('task', `/api/tasks/${taskId}`, file)
    }

    async function linkShare(taskId: number, sharePath: string): Promise<TaskDocument> {
        return $fetch<TaskDocument>(`${baseURL}/task_documents`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ task: `/api/tasks/${taskId}`, sharePath }),
            credentials: 'include',
        })
    }

    async function remove(id: number): Promise<void> {
        await api.delete(`/task_documents/${id}`, {}, {
            toastSuccessKey: 'taskDocuments.deleted',
        })
    }

    function getDownloadUrl(id: number): string {
        return `${baseURL}/task_documents/${id}/download`
    }

    async function getContent(id: number): Promise<string> {
        const response = await fetch(`${baseURL}/task_documents/${id}/download`, {
            credentials: 'include',
        })

        return response.text()
    }

    return { getByTask, upload, linkShare, remove, getDownloadUrl, getContent }
}
