package de.tsschulz.tt_tagebuch.shared.api

import de.tsschulz.tt_tagebuch.shared.api.http.AuthedHttpClient
import de.tsschulz.tt_tagebuch.shared.api.models.MemberGroupPhotoDto
import de.tsschulz.tt_tagebuch.shared.api.models.MemberGroupPhotoListResponse
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.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 MemberGroupPhotosApi(
    private val client: AuthedHttpClient,
) {
    suspend fun list(clubId: Int): List<MemberGroupPhotoDto> {
        val res: MemberGroupPhotoListResponse = client.http.get("/api/member-group-photos/$clubId").body()
        return res.photos
    }

    suspend fun upload(clubId: Int, imageBytes: ByteArray, title: String, description: String) {
        client.http.post("/api/member-group-photos/$clubId") {
            contentType(ContentType.MultiPart.FormData)
            setBody(
                MultiPartFormDataContent(
                    formData {
                        append("title", title.ifBlank { "Gruppenfoto" })
                        append("description", description)
                        append(
                            "image",
                            imageBytes,
                            Headers.build {
                                append(HttpHeaders.ContentType, "image/jpeg")
                                append(HttpHeaders.ContentDisposition, "filename=\"group.jpg\"")
                            },
                        )
                    },
                ),
            )
        }
    }

    suspend fun delete(clubId: Int, photoId: Int) {
        client.http.delete("/api/member-group-photos/$clubId/$photoId")
    }
}
