package com.prudas.app.config;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

/**
 * Fails application startup fast (rather than degrading silently into an
 * insecure state) when a production deployment is missing required secrets.
 * This is intentionally NOT active in the "dev" profile so local development
 * keeps working with the placeholder defaults in application.yml.
 */
@Component
@Profile("prod")
@RequiredArgsConstructor
public class StartupSecretsValidator {

    private final AppProperties appProperties;

    @Value("${spring.datasource.password:}")
    private String dbPassword;

    @PostConstruct
    void validate() {
        require(appProperties.jwt().secret() != null && appProperties.jwt().secret().length() >= 32,
                "JWT_SECRET must be set and at least 32 characters (256 bits) in production");
        require(dbPassword != null && !dbPassword.isBlank(),
                "DB_PASSWORD must be set in production");
        require(!appProperties.cors().allowedOrigins().isEmpty()
                        && !appProperties.cors().allowedOrigins().contains("*"),
                "CORS_ALLOWED_ORIGINS must be an explicit, non-wildcard origin list in production");
    }

    private void require(boolean condition, String message) {
        if (!condition) {
            throw new IllegalStateException("Startup aborted: " + message);
        }
    }
}
