package de.tsschulz.tt_tagebuch.shared.api

import de.tsschulz.tt_tagebuch.shared.models.*
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json

class ApiClient(private val baseUrl: String) {
    private val client = HttpClient {
        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true
                coerceInputValues = true
            })
        }
    }

    private var token: String? = null

    fun setToken(token: String?) {
        this.token = token
    }

    suspend fun login(email: String, password: String): LoginResponse {
        return client.post("$baseUrl/api/auth/login") {
            setBody(mapOf("email" to email, "password" to password))
            header("Content-Type", "application/json")
        }.body()
    }

    suspend fun getClubs(): List<Club> {
        return client.get("$baseUrl/api/clubs") {
            token?.let { header("Authorization", "Bearer $it") }
        }.body()
    }

    suspend fun getDiaryDates(clubId: Int): List<DiaryDate> {
        return client.get("$baseUrl/api/diary/$clubId") {
            token?.let { header("Authorization", "Bearer $it") }
        }.body()
    }

    suspend fun getDiaryParticipants(dateId: Int): List<Participant> {
        return client.get("$baseUrl/api/participants/$dateId") {
            token?.let { header("Authorization", "Bearer $it") }
        }.body()
    }

    suspend fun updateParticipantStatus(dateId: Int, memberId: Int, status: String): Boolean {
        return client.put("$baseUrl/api/participants/$dateId/$memberId/status") {
            setBody(mapOf("status" to status))
            header("Content-Type", "application/json")
            token?.let { header("Authorization", "Bearer $it") }
        }.status.value in 200..299
    }

    suspend fun getMembers(clubId: Int): List<Member> {
        return client.get("$baseUrl/api/clubmembers/get/$clubId/true") {
            token?.let { header("Authorization", "Bearer $it") }
        }.body()
    }

    suspend fun updateMember(clubId: Int, member: Member): Boolean {
        return client.post("$baseUrl/api/clubmembers/set/$clubId") {
            setBody(member)
            header("Content-Type", "application/json")
            token?.let { header("Authorization", "Bearer $it") }
        }.status.value in 200..299
    }
}
