/*
 *   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.ResponseError
import de.steamwar.plugins.SWAuthPrincipal
import de.steamwar.sql.SteamwarUser
import de.steamwar.sql.Token
import de.steamwar.util.TokenType
import de.steamwar.util.lifetime
import de.steamwar.util.type
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
import kotlin.time.Duration
import kotlin.time.toJavaDuration

@Serializable
data class UsernamePassword(val name: String, val password: String, val keepLoggedIn: Boolean = false)

@Serializable
data class ResponseToken(val token: String, val expires: String) {
    constructor(token: String, lifetime: Duration) : this(token, LocalDateTime.now().plus(lifetime.toJavaDuration()).toString())
}

@Serializable
data class AuthTokenResponse(val accessToken: ResponseToken, val refreshToken: ResponseToken? = null)

fun SteamwarUser.createAccessAndRefreshToken(keepLoggedIn: Boolean = false): AuthTokenResponse {
    val code = System.currentTimeMillis() % 1000
    val accessToken = Token.createToken("AT-${userName}-${code}", this)
    val refreshToken = if (keepLoggedIn) Token.createToken("RT-${userName}-${code}", this) else null

    return AuthTokenResponse(ResponseToken(accessToken, TokenType.ACCESS_TOKEN.lifetime), refreshToken?.let { ResponseToken(it, TokenType.REFRESH_TOKEN.lifetime) })
}

fun Route.configureAuth() {
    route("/auth") {
        post {
            val request = call.receive<UsernamePassword>()

            SteamwarUser.clear()
            val user = SteamwarUser.get(request.name)
            val valid = user?.verifyPassword(request.password) ?: false

            if (!valid) {
                call.respond(HttpStatusCode.Forbidden, ResponseError("Invalid username or password", "invalid"))
                return@post
            }

            call.respond(user.createAccessAndRefreshToken(request.keepLoggedIn))
        }
        put {
            val token = call.principal<SWAuthPrincipal>()

            if (token == null || token.token.type != TokenType.REFRESH_TOKEN) {
                call.respond(HttpStatusCode.Forbidden, ResponseError("Invalid token type", "invalid"))
                return@put
            }

            val code = token.token.name.substringAfterLast('-')

            Token.listUser(token.user)
                .filter { it.type == TokenType.ACCESS_TOKEN }
                .filter { it.name.endsWith(code) }
                .forEach { it.delete() }

            call.respond(token.user.createAccessAndRefreshToken(true))
        }
        delete {
            val token = call.principal<SWAuthPrincipal>()
            token?.let { t ->
                t.token.delete()
                val code = t.token.name.substringAfterLast('-')
                Token.listUser(token.user)
                    .filter { it.type == TokenType.REFRESH_TOKEN }
                    .filter { it.name.endsWith(code) }
                    .forEach { it.delete() }
            }

            call.respond(HttpStatusCode.OK)
        }
    }
}