use kube::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::crd_default_rules::{build_rule_container_restarting, build_rule_pod_failed};

#[derive(CustomResource, Debug, Serialize, Deserialize, Clone, JsonSchema)]
#[kube(
    group = "monitoring.coreos.com",
    version = "v1",
    kind = "PrometheusRule",
    plural = "prometheusrules",
    namespaced
)]
#[serde(rename_all = "camelCase")]
pub struct PrometheusRuleSpec {
    pub groups: Vec<RuleGroup>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RuleGroup {
    pub name: String,
    pub rules: Vec<Rule>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Rule {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alert: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expr: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub for_: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub labels: Option<std::collections::BTreeMap<String, String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub annotations: Option<std::collections::BTreeMap<String, String>>,
}

impl PrometheusRuleSpec {
    pub fn with_default_rules() -> Self {
        PrometheusRuleSpec {
            groups: vec![RuleGroup {
                name: "default.rules".into(),
                rules: vec![build_rule_container_restarting(), build_rule_pod_failed()],
            }],
        }
    }
}
