/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.routes

import de.steamwar.plugins.SWPermissionCheck
import de.steamwar.plugins.getUser
import de.steamwar.sql.SteamwarUser
import de.steamwar.sql.UserPerm
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable

@Serializable
data class RespondPrefix(val name: String, val colorCode: String, val chatPrefix: String)

@Serializable
data class RespondUserPerms(val prefixes: Map<String, RespondPrefix>, val perms: List<String>)

@Serializable
data class RespondUserPermsPrefix(val prefix: RespondPrefix, val perms: List<String>)

fun Route.configureUserPerms() {
    route("/perms") {
        install(SWPermissionCheck) {
            permission = UserPerm.MODERATION
        }
        get {
            val perms = mutableListOf<String>()
            val prefixes = mutableMapOf<String, RespondPrefix>()
            UserPerm.entries.forEach {
                if (it.name.startsWith("PREFIX_")) {
                    val prefix = UserPerm.prefixes[it]!!
                    prefixes[it.name] = RespondPrefix(it.name, prefix.colorCode, prefix.chatPrefix)
                } else {
                    perms.add(it.name)
                }
            }

            call.respond(RespondUserPerms(prefixes, perms))
        }
        route("/user/{id}") {
            get {
                val user = call.request.getUser()
                if (user == null) {
                    call.respond(HttpStatusCode.BadRequest)
                    return@get
                }
                val perms = mutableListOf<String>()
                var prefix = UserPerm.PREFIX_NONE
                user.perms().forEach {
                    if (it.name.startsWith("PREFIX_")) {
                        prefix = it
                    } else {
                        perms.add(it.name)
                    }
                }

                val prefixs = UserPerm.prefixes[prefix]!!

                call.respond(
                    RespondUserPermsPrefix(
                        RespondPrefix(prefix.name, prefixs.colorCode, prefixs.chatPrefix),
                        perms
                    )
                )
            }
            put("/prefix/{prefix}") {
                val (user, prefix) = call.receivePermission("prefix", isPrefix = true)
                    ?: return@put

                user.perms().filter { it.name.startsWith("PREFIX_") }.forEach {
                    UserPerm.removePerm(user, it)
                }

                UserPerm.addPerm(user, UserPerm.entries.find { it == prefix }!!)
                call.respond(HttpStatusCode.Accepted)
            }
            put("/{perm}") {
                val (user, permission) = call.receivePermission()
                    ?: return@put

                if (!user.hasPerm(permission)) {
                    UserPerm.addPerm(user, permission)
                    call.respond(HttpStatusCode.Accepted)
                    return@put
                }
                call.respond(HttpStatusCode.NoContent)
            }
            delete("/{perm}") {
                val (user, permission) = call.receivePermission()
                    ?: return@delete

                if (user.hasPerm(permission)) {
                    UserPerm.removePerm(user, permission)
                    call.respond(HttpStatusCode.Accepted)
                    return@delete
                }
                call.respond(HttpStatusCode.NoContent)
            }
        }
    }
}

suspend fun ApplicationCall.receivePermission(
    fieldName: String = "perm",
    isPrefix: Boolean = false
): Pair<SteamwarUser, UserPerm>? {
    val user = request.getUser()
    if (user == null) {
        respond(HttpStatusCode.BadRequest)
        return null
    }

    val perm = parameters[fieldName]
    val permission = UserPerm.entries.find { it.name == perm }
    if (perm == null || perm.startsWith("PREFIX_") != isPrefix || permission == null) {
        println(perm)
        respond(HttpStatusCode.BadRequest)
        return null
    }

    return user to permission
}