package dev.inmo.postssystem.features.auth.server

import dev.inmo.postssystem.features.auth.common.AuthToken
import dev.inmo.postssystem.features.common.common.Milliseconds
import dev.inmo.postssystem.features.auth.common.tokenSessionKey
import dev.inmo.micro_utils.ktor.server.configurators.ApplicationSessionsConfigurator
import io.ktor.sessions.*
import java.util.concurrent.TimeUnit

class SessionAuthenticationConfigurator(
    private val maxAge: Milliseconds
) : ApplicationSessionsConfigurator.Element {
    private val maxAgeInSeconds = TimeUnit.MILLISECONDS.toSeconds(maxAge)
    override fun Sessions.Configuration.invoke() {
        cookie<AuthToken>(tokenSessionKey) {
            cookie.maxAgeInSeconds = maxAgeInSeconds
            serializer = object : SessionSerializer<AuthToken> {
                override fun deserialize(text: String): AuthToken = AuthToken(text)
                override fun serialize(session: AuthToken): String = session.string
            }
        }
    }
}
