package com.writeoff.module.observability.job;

import com.writeoff.module.observability.service.ObservabilityService;
import com.writeoff.security.AuthContext;
import com.writeoff.security.AuthScope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class AlertRuleAutoEvaluateJob {
    private final ObservabilityService observabilityService;
    private final JdbcTemplate jdbcTemplate;
    private final boolean enabled;
    private final int recoveryWindowMinute;

    public AlertRuleAutoEvaluateJob(ObservabilityService observabilityService,
                                    JdbcTemplate jdbcTemplate,
                                    @Value("${app.observability.auto-evaluate.enabled:true}") boolean enabled,
                                    @Value("${app.observability.recovery-window-minute:10}") int recoveryWindowMinute) {
        this.observabilityService = observabilityService;
        this.jdbcTemplate = jdbcTemplate;
        this.enabled = enabled;
        this.recoveryWindowMinute = recoveryWindowMinute;
    }

    @Scheduled(fixedDelayString = "${app.observability.auto-evaluate.interval-ms:60000}")
    public void run() {
        if (!enabled) {
            return;
        }
        List<Long> tenantIds = jdbcTemplate.queryForList(
                "SELECT id FROM tenant WHERE is_deleted=0 AND status='ENABLED' ORDER BY id ASC",
                Long.class
        );
        for (Long tenantId : tenantIds) {
            try {
                AuthContext.set(0L, tenantId, AuthScope.TENANT);
                observabilityService.evaluateRulesAuto(recoveryWindowMinute);
            } finally {
                AuthContext.clear();
            }
        }
    }
}
