package com.yimeng.okr.config;

import com.yimeng.okr.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("prod")
public class ProductionStartupValidator implements CommandLineRunner {

    private static final String DEFAULT_JWT_SECRET = "yimeng-ai-okr-secret-key-2026-must-be-at-least-256-bits-long";
    private static final String DEFAULT_ADMIN_PASSWORD = "emoon123456";

    private final String jwtSecret;
    private final String superAdminPassword;
    private final String allowedOrigins;

    public ProductionStartupValidator(
            @Value("${app.jwt.secret}") String jwtSecret,
            @Value("${app.super-admin.password}") String superAdminPassword,
            @Value("${app.cors.allowed-origins}") String allowedOrigins) {
        this.jwtSecret = jwtSecret;
        this.superAdminPassword = superAdminPassword;
        this.allowedOrigins = allowedOrigins;
    }

    @Override
    public void run(String... args) {
        validate();
    }

    void validate() {
        if (jwtSecret == null || jwtSecret.isBlank() || DEFAULT_JWT_SECRET.equals(jwtSecret) || jwtSecret.length() < 32) {
            throw new BusinessException("生产环境必须配置强随机 APP_JWT_SECRET，长度至少 32 字符");
        }
        if (superAdminPassword == null || superAdminPassword.isBlank()
                || DEFAULT_ADMIN_PASSWORD.equals(superAdminPassword) || superAdminPassword.length() < 12) {
            throw new BusinessException("生产环境必须配置强初始 APP_SUPER_ADMIN_PASSWORD，且不能使用默认密码");
        }
        if (allowedOrigins == null || allowedOrigins.isBlank()
                || allowedOrigins.contains("localhost") || allowedOrigins.contains("127.0.0.1")
                || allowedOrigins.contains("*")) {
            throw new BusinessException("生产环境必须配置明确的 APP_CORS_ORIGINS，不能使用本地或通配域名");
        }
    }
}
