package com.codebyte.api.config.ssl;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.ssl.SslBundleRegistrar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Wires the PEM SSL trio. The bundle registrar is always present (a no-op when disabled); the
 * loaded material, health indicator, and expiry metric exist only when {@code
 * app.ssl.enabled=true}.
 */
@Configuration
public class SslConfig {

    @Bean
    SslBundleRegistrar pemSslBundleRegistrar(SslProperties properties) {
        return new PemSslBundleRegistrar(properties);
    }

    @Bean
    @ConditionalOnProperty(prefix = "app.ssl", name = "enabled", havingValue = "true")
    PemSslMaterial sslMaterial(SslProperties properties) {
        return new PemSslLoader(properties).load();
    }

    @Bean("sslHealthIndicator")
    @ConditionalOnProperty(prefix = "app.ssl", name = "enabled", havingValue = "true")
    SslCertificateHealthIndicator sslHealthIndicator(PemSslMaterial material) {
        return new SslCertificateHealthIndicator(material);
    }

    @Bean
    @ConditionalOnProperty(prefix = "app.ssl", name = "enabled", havingValue = "true")
    SslMetrics sslMetrics(PemSslMaterial material, MeterRegistry registry) {
        return new SslMetrics(material, registry);
    }
}
