package dev.inmo.postssystem.features.roles.server

import dev.inmo.postssystem.features.roles.common.*
import dev.inmo.micro_utils.ktor.server.*
import dev.inmo.micro_utils.ktor.server.configurators.ApplicationRoutingConfigurator
import io.ktor.application.call
import io.ktor.auth.authenticate
import io.ktor.routing.*
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.serializer

class RolesStorageWriteServerRoutesConfigurator<T : Role>(
    private val storage: WriteRolesStorage<T>,
    private val serializer: KSerializer<T>,
    private val includeAuthKey: String,
    private val excludeAuthKey: String = includeAuthKey,
    private val unifiedRouter: UnifiedRouter
) : ApplicationRoutingConfigurator.Element {
    override fun Route.invoke() {
        route(usersRolesRootPathPart) {
            val wrapperSerializer = RolesStorageIncludeExcludeWrapper.serializer(
                serializer
            )
            unifiedRouter.apply {
                authenticate(includeAuthKey) {
                    post(usersRolesIncludePathPart) {
                        val wrapper = uniload(wrapperSerializer)

                        unianswer(
                            Boolean.serializer(),
                            storage.include(
                                wrapper.subject,
                                wrapper.userRole
                            )
                        )
                    }
                }
                authenticate(excludeAuthKey) {
                    post(usersRolesExcludePathPart) {
                        val wrapper = uniload(wrapperSerializer)

                        unianswer(
                            Boolean.serializer(),
                            storage.exclude(
                                wrapper.subject,
                                wrapper.userRole
                            )
                        )
                    }
                }
            }
        }
    }
}
