package com.davos.assessment.config;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ProductionLockValidator implements ApplicationRunner {
  private final boolean enforceProductionSecrets;
  private final String jwtSecret;
  private final String adminEmail;
  private final String adminPassword;
  private final String seedInviteCode;

  public ProductionLockValidator(
      @Value("${app.lock.enforce-production-secrets:false}") boolean enforceProductionSecrets,
      @Value("${app.jwt.secret}") String jwtSecret,
      @Value("${app.admin.email}") String adminEmail,
      @Value("${app.admin.password}") String adminPassword,
      @Value("${app.invite.seed-code}") String seedInviteCode) {
    this.enforceProductionSecrets = enforceProductionSecrets;
    this.jwtSecret = jwtSecret;
    this.adminEmail = adminEmail;
    this.adminPassword = adminPassword;
    this.seedInviteCode = seedInviteCode;
  }

  @Override
  public void run(ApplicationArguments args) {
    if (!enforceProductionSecrets) return;

    List<String> errors = new ArrayList<>();
    if (jwtSecret == null || jwtSecret.length() < 32 || jwtSecret.contains("change-this")) {
      errors.add("JWT_SECRET 不符合生产要求（至少 32 位且不能使用默认值）");
    }
    if ("admin@davos.test".equalsIgnoreCase(adminEmail.trim())) {
      errors.add("ADMIN_EMAIL 仍为默认值");
    }
    if ("Admin123456".equals(adminPassword)) {
      errors.add("ADMIN_PASSWORD 仍为默认值");
    }
    if ("DAVOS2026".equalsIgnoreCase(seedInviteCode.trim())) {
      errors.add("SEED_INVITE_CODE 仍为默认值");
    }

    if (!errors.isEmpty()) {
      throw new IllegalStateException("生产锁定校验未通过: " + String.join("；", errors));
    }
  }
}
