package de.tsschulz.tt_tagebuch.shared.api

import de.tsschulz.tt_tagebuch.shared.api.http.AuthedHttpClient
import de.tsschulz.tt_tagebuch.shared.api.models.TeamDocumentDto
import de.tsschulz.tt_tagebuch.shared.api.models.TeamDocumentParseEnvelopeDto
import io.ktor.client.call.body
import io.ktor.client.request.delete
import io.ktor.client.request.forms.MultiPartFormDataContent
import io.ktor.client.request.forms.formData
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.contentType

class TeamDocumentsApi(
    private val client: AuthedHttpClient,
) {
    suspend fun listByClubTeam(clubTeamId: Int): List<TeamDocumentDto> {
        return client.http.get("/api/team-documents/club-team/$clubTeamId").body()
    }

    suspend fun upload(
        clubTeamId: Int,
        documentType: String,
        bytes: ByteArray,
        fileName: String,
        mimeType: String,
    ): TeamDocumentDto {
        return client.http.post("/api/team-documents/club-team/$clubTeamId/upload") {
            contentType(ContentType.MultiPart.FormData)
            setBody(
                MultiPartFormDataContent(
                    formData {
                        append("documentType", documentType)
                        append(
                            "document",
                            bytes,
                            Headers.build {
                                append(HttpHeaders.ContentType, mimeType)
                                append(HttpHeaders.ContentDisposition, "filename=\"$fileName\"")
                            },
                        )
                    },
                ),
            )
        }.body()
    }

    suspend fun parse(documentId: Int, leagueId: Int): TeamDocumentParseEnvelopeDto {
        return client.http.post("/api/team-documents/$documentId/parse") {
            parameter("leagueid", leagueId)
        }.body()
    }

    suspend fun download(documentId: Int): ByteArray {
        return client.http.get("/api/team-documents/$documentId/download").body()
    }

    suspend fun delete(documentId: Int) {
        client.http.delete("/api/team-documents/$documentId")
    }
}
