/*
 *   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.plugins

import de.steamwar.sql.Token
import de.steamwar.util.TokenType
import de.steamwar.util.isValid
import de.steamwar.util.type
import io.ktor.http.*
import io.ktor.http.auth.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.ratelimit.*
import kotlinx.serialization.json.Json
import kotlin.time.Duration.Companion.seconds

fun Application.configurePlugins() {
    install(CORS) {
        allowMethod(HttpMethod.Options)
        allowMethod(HttpMethod.Get)
        allowMethod(HttpMethod.Post)
        allowMethod(HttpMethod.Put)
        allowMethod(HttpMethod.Delete)
        allowHeader(HttpHeaders.Authorization)
        allowHeader(HttpHeaders.AccessControlAllowOrigin)
        allowHeader(HttpHeaders.ContentType)
        anyHost()
        allowXHttpMethodOverride()
    }
    install(RateLimit) {
        global {
            rateLimiter(limit = 60, refillPeriod = 60.seconds)
            requestKey {
                it.request.headers["X-Forwarded-For"] ?: it.request.local.remoteHost
            }
            requestWeight { applicationCall, _ ->
                if(!applicationCall.request.headers.contains("X-Forwarded-For")) {
                    0
                } else {
                    1
                }
            }
        }
    }
    authentication {
        bearer("sw-auth") {
            realm = "SteamWar API"
            authenticate { call ->
                val token = Token.getTokenByCode(call.token)
                if (token == null) {
                    null
                } else {
                    if (!token.isValid) {
                        token.delete()
                        return@authenticate null
                    }
                    if (token.type == TokenType.REFRESH_TOKEN) {
                        token.delete()
                    }

                    SWAuthPrincipal(token, token.owner)
                }
            }
        }
    }
    install(ContentNegotiation) {
        json(Json)
    }
    install(ErrorLogger)
}
