use k8s_openapi::NamespaceResourceScope;
use kube::{Api, Client, Error, Resource, api::PostParams};
use serde::de::DeserializeOwned;

pub struct K8sClient {
    client: Client,
}

impl K8sClient {
    pub async fn try_default() -> Result<Self, Error> {
        Ok(Self {
            client: Client::try_default().await?,
        })
    }

    pub async fn apply_all<
        K: Resource<Scope = NamespaceResourceScope>
            + std::fmt::Debug
            + Sync
            + DeserializeOwned
            + Default
            + serde::Serialize
            + Clone,
    >(
        &self,
        resource: &Vec<K>,
    ) -> Result<Vec<K>, kube::Error>
    where
        <K as kube::Resource>::DynamicType: Default,
    {
        let mut result = vec![];
        for r in resource.iter() {
            let api: Api<K> = Api::all(self.client.clone());
            result.push(api.create(&PostParams::default(), &r).await?);
        }
        Ok(result)
    }

    pub async fn apply_namespaced<K>(&self, resource: &Vec<K>) -> Result<K, Error>
    where
        K: Resource<Scope = NamespaceResourceScope>
            + Clone
            + std::fmt::Debug
            + DeserializeOwned
            + serde::Serialize
            + Default,
        <K as kube::Resource>::DynamicType: Default,
    {
        for r in resource.iter() {
            let api: Api<K> = Api::default_namespaced(self.client.clone());
            api.create(&PostParams::default(), &r).await?;
        }
        todo!("")
    }
}
