package com.betriebsratkanzlei.legalconsenthub.security

import org.springframework.core.convert.converter.Converter
import org.springframework.security.authentication.AbstractAuthenticationToken
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.stereotype.Component

@Component
class CustomJwtAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {
    override fun convert(jwt: Jwt): AbstractAuthenticationToken {
        val authorities: Collection<GrantedAuthority> = emptyList()

        val userId = jwt.getClaimAsString("id")
        val username = jwt.getClaimAsString("name")
        val organizationId = jwt.getClaimAsString("organizationId")
        val roles = jwt.getClaimAsStringList("roles") ?: emptyList()

        val principal = CustomJwtTokenPrincipal(userId, username, organizationId, roles)

        return CustomJwtAuthentication(jwt, principal, authorities)
    }
}
