package dev.inmo.postssystem.services.posts.client

import dev.inmo.micro_utils.common.MPPFile
import dev.inmo.micro_utils.common.filename
import dev.inmo.micro_utils.ktor.client.UnifiedRequester
import dev.inmo.micro_utils.ktor.client.inputProvider
import dev.inmo.postssystem.features.common.common.mimeType
import dev.inmo.postssystem.features.files.common.FileId
import io.ktor.client.features.onUpload
import io.ktor.client.request.forms.formData
import io.ktor.client.request.forms.submitFormWithBinaryData
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders

internal actual suspend fun UnifiedRequester.tempUpload(
    fullTempUploadDraftPath: String,
    file: MPPFile,
    onUpload: (Long, Long) -> Unit
): FileId {
    val inputProvider = file.inputProvider()
    val fileId = client.submitFormWithBinaryData<String>(
        fullTempUploadDraftPath,
        formData = formData {
            append(
                "data",
                inputProvider,
                Headers.build {
                    append(HttpHeaders.ContentType, file.mimeType.raw)
                    append(HttpHeaders.ContentDisposition, "filename=\"${file.filename.string}\"")
                }
            )
        }
    ) {
        onUpload(onUpload)
    }
    return FileId(fileId)
}

