package de.tsschulz.tt_tagebuch.shared.api

import de.tsschulz.tt_tagebuch.shared.api.http.AuthedHttpClient
import de.tsschulz.tt_tagebuch.shared.api.models.AvailableRoleDto
import de.tsschulz.tt_tagebuch.shared.api.models.ClubPermissionMemberDto
import de.tsschulz.tt_tagebuch.shared.api.models.PermissionResourceDto
import de.tsschulz.tt_tagebuch.shared.api.models.UpdateUserApprovedBody
import de.tsschulz.tt_tagebuch.shared.api.models.UpdateUserCustomPermissionsBody
import de.tsschulz.tt_tagebuch.shared.api.models.UpdateUserRoleBody
import de.tsschulz.tt_tagebuch.shared.api.models.UserClubPermissions
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.request.put
import io.ktor.client.request.setBody

class PermissionsApi(
    private val client: AuthedHttpClient,
) {
    suspend fun getUserPermissions(clubId: Int): UserClubPermissions {
        return client.http.get("/api/permissions/$clubId").body()
    }

    suspend fun listAvailableRoles(): List<AvailableRoleDto> {
        return client.http.get("/api/permissions/roles/available").body()
    }

    suspend fun getPermissionStructure(): Map<String, PermissionResourceDto> {
        return client.http.get("/api/permissions/structure/all").body()
    }

    suspend fun listClubMembersWithPermissions(clubId: Int, cacheBust: Boolean = false): List<ClubPermissionMemberDto> {
        return client.http.get("/api/permissions/$clubId/members") {
            if (cacheBust) parameter("t", kotlin.random.Random.nextLong().toString())
        }.body()
    }

    suspend fun updateUserRole(clubId: Int, userId: Int, role: String) {
        client.http.put("/api/permissions/$clubId/user/$userId/role") {
            setBody(UpdateUserRoleBody(role = role))
        }
    }

    suspend fun updateUserStatus(clubId: Int, userId: Int, approved: Boolean) {
        client.http.put("/api/permissions/$clubId/user/$userId/status") {
            setBody(UpdateUserApprovedBody(approved = approved))
        }
    }

    suspend fun updateUserCustomPermissions(clubId: Int, userId: Int, permissions: kotlinx.serialization.json.JsonObject) {
        client.http.put("/api/permissions/$clubId/user/$userId/permissions") {
            setBody(UpdateUserCustomPermissionsBody(permissions = permissions))
        }
    }
}

