package de.krisenvorrat.server.plugins

import io.ktor.server.application.*
import io.ktor.server.plugins.ratelimit.*
import io.ktor.server.request.*
import kotlin.time.Duration.Companion.minutes

internal val RATE_LIMIT_AUTH = RateLimitName("auth")
internal val RATE_LIMIT_MESSAGES = RateLimitName("messages")
internal val RATE_LIMIT_INVENTORY = RateLimitName("inventory")
internal val RATE_LIMIT_ADMIN = RateLimitName("admin")

internal fun Application.configureRateLimiting() {
    install(RateLimit) {
        // Auth endpoints: 10 requests per minute per IP (brute-force protection)
        register(RATE_LIMIT_AUTH) {
            rateLimiter(limit = 10, refillPeriod = 1.minutes)
            requestKey { call ->
                call.request.local.remoteAddress
            }
        }

        // Message endpoints: 30 requests per minute per user
        register(RATE_LIMIT_MESSAGES) {
            rateLimiter(limit = 30, refillPeriod = 1.minutes)
            requestKey { call ->
                call.request.local.remoteAddress
            }
        }

        // Inventory endpoints: 60 requests per minute per user
        register(RATE_LIMIT_INVENTORY) {
            rateLimiter(limit = 60, refillPeriod = 1.minutes)
            requestKey { call ->
                call.request.local.remoteAddress
            }
        }

        // Admin endpoints: 20 requests per minute per user
        register(RATE_LIMIT_ADMIN) {
            rateLimiter(limit = 20, refillPeriod = 1.minutes)
            requestKey { call ->
                call.request.local.remoteAddress
            }
        }
    }
}
