package com.cameleer.server.app.alerting.eval;

import com.cameleer.server.core.alerting.AlertRule;
import com.cameleer.server.core.alerting.ConditionKind;
import com.cameleer.server.core.alerting.DeploymentStateCondition;
import com.cameleer.server.core.runtime.App;
import com.cameleer.server.core.runtime.AppRepository;
import com.cameleer.server.core.runtime.Deployment;
import com.cameleer.server.core.runtime.DeploymentRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class DeploymentStateEvaluator implements ConditionEvaluator<DeploymentStateCondition> {

    private final AppRepository appRepo;
    private final DeploymentRepository deploymentRepo;

    public DeploymentStateEvaluator(AppRepository appRepo, DeploymentRepository deploymentRepo) {
        this.appRepo        = appRepo;
        this.deploymentRepo = deploymentRepo;
    }

    @Override
    public ConditionKind kind() { return ConditionKind.DEPLOYMENT_STATE; }

    @Override
    public EvalResult evaluate(DeploymentStateCondition c, AlertRule rule, EvalContext ctx) {
        String appSlug = c.scope() != null ? c.scope().appSlug() : null;
        App app = (appSlug != null)
                ? appRepo.findByEnvironmentIdAndSlug(rule.environmentId(), appSlug).orElse(null)
                : null;

        if (app == null) return EvalResult.Clear.INSTANCE;

        Set<String> wanted = Set.copyOf(c.states());
        List<Deployment> hits = deploymentRepo.findByAppId(app.id()).stream()
                .filter(d -> wanted.contains(d.status().name()))
                .toList();

        if (hits.isEmpty()) return EvalResult.Clear.INSTANCE;

        Deployment d = hits.get(0);
        return new EvalResult.Firing(
                (double) hits.size(), null,
                Map.of(
                        "deployment", Map.of(
                                "id",     d.id().toString(),
                                "status", d.status().name()
                        ),
                        "app", Map.of("slug", app.slug())
                )
        );
    }
}
