/*
 *   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.SWAuthPrincipal
import de.steamwar.plugins.SWPermissionCheck
import de.steamwar.sql.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable

@Serializable
data class UserStats(val eventFightParticipation: Int, val eventParticipation: Int, val acceptedSchematics: Int, val fights: Int, val playtime: Double) {
    constructor(user: SteamwarUser) : this(
        getEventFightParticipation(user)
            ?: 0,
        getEventParticipation(user)
            ?: 0,
        getAcceptedSchematics(user)
            ?: 0,
        getFightCount(user)
            ?: 0,
        user.getOnlinetime() / 3600.0
    )
}

fun Route.configureStats() {
    route("/stats") {
        get("/ranked/{gamemode}") {
            val gamemode = call.parameters["gamemode"]
                ?: return@get call.respond(HttpStatusCode.NotFound)

            @Serializable
            data class RankedUser(val name: String, val elo: Int)

            call.respond(getRankedList(gamemode).map { RankedUser(it.first, it.second) })
        }
        get("/fights") {
            val list = getFightList()

            @Serializable
            data class Fight(val date: String, val gamemode: String, val count: Int)

            call.respond(list.map { Fight(it.first, it.second, it.third) })
        }
        route("/user") {
            install(SWPermissionCheck)
            get {
                val user = call.authentication.principal<SWAuthPrincipal>()

                if (user == null) {
                    call.respond(HttpStatusCode.NotFound, "User not found")
                    return@get
                }

                call.respond(UserStats(user.user))
            }
        }
    }
}