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

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

    async function getByReport(reportId: number): Promise<ReportDocument[]> {
        const data = await api.get<HydraCollection<ReportDocument>>('/report_documents', {
            commercialReport: `/api/commercial_reports/${reportId}`,
        })
        return extractHydraMembers(data)
    }

    async function upload(reportId: number, file: File): Promise<ReportDocument> {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('commercialReport', `/api/commercial_reports/${reportId}`)

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

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

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

    return { getByReport, upload, remove, getDownloadUrl }
}
