use k8s_openapi::api::apps::v1::Deployment;
use serde::Serialize;
use serde_json::json;

use crate::{
    interpret::Interpret,
    score::Score,
    topology::{K8sclient, Topology},
};

use super::resource::{K8sResourceInterpret, K8sResourceScore};

#[derive(Debug, Clone, Serialize)]
pub struct K8sDeploymentScore {
    pub name: String,
    pub image: String,
    pub namespace: Option<String>,
    pub env_vars: serde_json::Value,
}

impl<T: Topology + K8sclient> Score<T> for K8sDeploymentScore {
    fn create_interpret(&self) -> Box<dyn Interpret<T>> {
        let deployment = json!(
            {
                "metadata": {
                    "name": self.name
                },
                "spec": {
                    "selector": {
                        "matchLabels":  {
                            "app": self.name
                        },
                    },
                    "template": {
                        "metadata": {
                            "labels": {
                                "app": self.name
                            },
                        },
                        "spec": {
                            "containers": [
                                {
                                    "image": self.image,
                                    "name": self.name,
                                    "imagePullPolicy": "Always",
                                    "env": self.env_vars,
                                }
                            ]
                        }
                    }
                }
            }
        );

        let deployment: Deployment = serde_json::from_value(deployment).unwrap();
        Box::new(K8sResourceInterpret {
            score: K8sResourceScore::single(deployment.clone(), self.namespace.clone()),
        })
    }

    fn name(&self) -> String {
        "K8sDeploymentScore".to_string()
    }
}
