package de.tsschulz.tt_tagebuch.shared.api

import de.tsschulz.tt_tagebuch.shared.api.http.AuthedHttpClient
import de.tsschulz.tt_tagebuch.shared.api.models.CreateClubTrainingGroupBody
import de.tsschulz.tt_tagebuch.shared.api.models.TrainingGroupDto
import de.tsschulz.tt_tagebuch.shared.api.models.UpdateClubTrainingGroupBody
import io.ktor.client.call.body
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.put
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.contentType

class TrainingGroupsApi(
    private val client: AuthedHttpClient,
) {
    suspend fun listGroups(clubId: Int): List<TrainingGroupDto> {
        return client.http.get("/api/training-groups/$clubId").body()
    }

    suspend fun listMemberGroups(clubId: Int, memberId: Int): List<TrainingGroupDto> {
        return client.http.get("/api/training-groups/$clubId/member/$memberId").body()
    }

    suspend fun addMemberToGroup(clubId: Int, groupId: Int, memberId: Int) {
        client.http.post("/api/training-groups/$clubId/$groupId/member/$memberId") {
            contentType(ContentType.Application.Json)
            setBody("{}")
        }
    }

    suspend fun removeMemberFromGroup(clubId: Int, groupId: Int, memberId: Int) {
        client.http.delete("/api/training-groups/$clubId/$groupId/member/$memberId")
    }

    suspend fun createGroup(clubId: Int, name: String): TrainingGroupDto {
        return client.http.post("/api/training-groups/$clubId") {
            contentType(ContentType.Application.Json)
            setBody(CreateClubTrainingGroupBody(name = name.trim()))
        }.body()
    }

    suspend fun updateGroup(clubId: Int, groupId: Int, name: String, sortOrder: Int?): TrainingGroupDto {
        return client.http.put("/api/training-groups/$clubId/$groupId") {
            contentType(ContentType.Application.Json)
            setBody(UpdateClubTrainingGroupBody(name = name.trim(), sortOrder = sortOrder))
        }.body()
    }

    suspend fun deleteGroup(clubId: Int, groupId: Int) {
        client.http.delete("/api/training-groups/$clubId/$groupId")
    }
}
