package llc.arma.fleet.monitor.presentation.graphql

import llc.arma.fleet.monitor.data.entity.UserEntity
import llc.arma.fleet.monitor.domain.service.AuthService
import llc.arma.fleet.monitor.presentation.model.AuthPayload
import llc.arma.fleet.monitor.presentation.model.LoginPayload
import llc.arma.fleet.monitor.presentation.model.RefreshSessionPayload
import llc.arma.fleet.monitor.security.AuthTokenStore
import jakarta.servlet.http.HttpServletRequest
import org.springframework.graphql.data.method.annotation.Argument
import org.springframework.graphql.data.method.annotation.MutationMapping
import org.springframework.graphql.data.method.annotation.QueryMapping
import org.springframework.stereotype.Controller
import java.security.Principal

@Controller
class AuthGraphQlController(
    private val authService: AuthService,
    private val tokenStore: AuthTokenStore,
) {
    @MutationMapping
    fun login(@Argument payload: LoginPayload): AuthPayload = authService.login(payload)

    @MutationMapping
    fun refreshSession(@Argument payload: RefreshSessionPayload): AuthPayload = authService.refreshSession(payload)

    @MutationMapping
    fun logout(request: HttpServletRequest): Boolean {
        tokenStore.revoke(extractToken(request))

        return true
    }

    @QueryMapping
    fun currentUser(principal: Principal?): UserEntity? = authService.getCurrentUser(principal?.name?.toLongOrNull())

    private fun extractToken(request: HttpServletRequest): String? {
        return request.getHeader("Authorization")
            ?.removePrefix("Bearer ")
            ?: request.cookies?.firstOrNull { it.name == "Access-token" }?.value
    }
}
