package scheduler

import (
	"context"
	"fmt"
	"time"

	"github.com/prometheus/common/model"
)

type AlertsCluster struct {
	Severity string
	Event    string
	Score    int
}

type AlertsNode struct {
	NodeID   string
	Event    string
	Severity string
	Score    int
}

func (s *Scheduler) GetAlertCluster() ([]AlertsCluster, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// On récupère les alertes sur les noeuds
	query := fmt.Sprintf("ALERTS_FOR_STATE{cluster_id=\"%s\", type=\"deevirt_default\"}\n", s.Config.ClusterID)
	res, _, err := s.Api.Query(ctx, query, time.Now())
	if err != nil {
		return nil, fmt.Errorf("erreur lors de la récupération des alertes filtrées: %v", err)
	}

	data := []AlertsCluster{}
	for _, res := range res.(model.Vector) {
		data = append(data, AlertsCluster{
			Event:    string(res.Metric["event"]),
			Severity: string(res.Metric["severity"]),
			Score:    int(res.Value),
		})
	}

	return data, nil
}

func (s *Scheduler) GetAlertNodes() ([]AlertsNode, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// On récupère les alertes sur les noeuds
	query := fmt.Sprintf("ALERTS_FOR_STATE{cluster_id=\"%s\", type=\"deevirt_node_default\"}\n", s.Config.ClusterID)
	res, _, err := s.Api.Query(ctx, query, time.Now())
	if err != nil {
		return nil, fmt.Errorf("erreur lors de la récupération des alertes filtrées: %v", err)
	}

	data := []AlertsNode{}
	for _, res := range res.(model.Vector) {
		data = append(data, AlertsNode{
			Event:    string(res.Metric["event"]),
			NodeID:   string(res.Metric["node_id"]),
			Severity: string(res.Metric["severity"]),
			Score:    int(res.Value),
		})
	}

	return data, nil
}
