package gaf3.core.services.auth

import gaf3.core.cloud.GafCloudConfiguration
import gaf3.core.services.bff.BffServiceConfiguration
import io.jsonwebtoken.SignatureAlgorithm
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import java.security.Key
import javax.crypto.spec.SecretKeySpec

@Configuration
@EnableConfigurationProperties(GafAuthConfigure::class)
@EntityScan(basePackages = ["gaf3.core.services"])
@Import(GafCloudConfiguration::class, BffServiceConfiguration::class)
class GafAuthConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = ["jwtSigningKey"])
    @Qualifier("jwtSigningKey")
    fun jwtSigningKey(config: GafAuthConfigure): Key {
        val secretKeyBytes = config.jwtSecret?.toByteArray()?.copyOf(32)
        val alg: SignatureAlgorithm = SignatureAlgorithm.HS256
        return SecretKeySpec(secretKeyBytes, alg.jcaName)
    }
}