package com.cameleer.server.app.security;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration class that creates security service beans and validates
 * that required security properties are set.
 * <p>
 * Fails fast on startup if {@code CAMELEER_SERVER_SECURITY_BOOTSTRAPTOKEN} is not set.
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityBeanConfig {

    @Bean
    public JwtServiceImpl jwtService(SecurityProperties properties) {
        return new JwtServiceImpl(properties);
    }

    @Bean
    public Ed25519SigningServiceImpl ed25519SigningService(SecurityProperties properties) {
        String secret = properties.getJwtSecret();
        if (secret == null || secret.isBlank()) {
            return Ed25519SigningServiceImpl.ephemeral();
        }
        return new Ed25519SigningServiceImpl(secret);
    }

    @Bean
    public BootstrapTokenValidator bootstrapTokenValidator(SecurityProperties properties) {
        return new BootstrapTokenValidator(properties);
    }

    @Bean
    public InitializingBean bootstrapTokenValidation(SecurityProperties properties) {
        return () -> {
            String token = properties.getBootstrapToken();
            if (token == null || token.isBlank()) {
                throw new IllegalStateException(
                        "CAMELEER_SERVER_SECURITY_BOOTSTRAPTOKEN environment variable must be set");
            }
        };
    }

}
