package cn.novalon.gym.manage.gateway.config;

import cn.novalon.gym.manage.gateway.service.impl.JwtKeyServiceImpl;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class JwtKeyManagementConfig {

    private static final Logger logger = LoggerFactory.getLogger(JwtKeyManagementConfig.class);

    @Autowired
    private JwtKeyServiceImpl jwtKeyService;

    @PostConstruct
    public void initialize() {
        jwtKeyService.initializeKeys();
        logger.info("JWT key management service initialized");
    }

    @Scheduled(fixedRate = 24 * 60 * 60 * 1000, initialDelay = 60 * 1000)
    public void scheduledKeyRotationCheck() {
        try {
            logger.debug("Checking JWT key rotation status");
            
            if (jwtKeyService.shouldRotateKey()) {
                logger.info("JWT key rotation triggered");
                jwtKeyService.rotateKey();
            } else {
                logger.debug("JWT key rotation not needed at this time");
            }
            
        } catch (Exception e) {
            logger.error("Error during scheduled JWT key rotation check", e);
        }
    }
}