//! Rhai wrappers for Registry deployment

use crate::kubernetes::RegistryDeployerBuilder;
use rhai::EvalAltResult;
use super::runtime::{get_runtime, to_rhai_err};

/// Rhai wrapper for RegistryDeployerBuilder
#[derive(Clone)]
pub struct RegistryDeployerBuilderRhai {
    builder: RegistryDeployerBuilder,
}

impl RegistryDeployerBuilderRhai {
    /// Create a new RegistryDeployerBuilderRhai wrapper
    pub fn new(builder: RegistryDeployerBuilder) -> Self {
        Self { builder }
    }

    /// Set node port
    pub fn node_port(mut self, port: i64) -> Self {
        self.builder = self.builder.node_port(port as u16);
        self
    }

    /// Set timeout in seconds
    pub fn timeout(mut self, secs: i64) -> Self {
        self.builder = self.builder.timeout_secs(secs as u64);
        self
    }

    /// Set storage size (in GB)
    pub fn storage_size(mut self, size: i64) -> Self {
        self.builder = self.builder.persistence(true, format!("{}Gi", size));
        self
    }

    /// Deploy the registry
    pub fn deploy(&self) -> Result<RegistryDeployerRhai, Box<EvalAltResult>> {
        let builder = self.builder.clone();
        let rt = get_runtime();
        rt.block_on(async { builder.deploy().await.map_err(|e| format!("Deploy error: {}", e)) })
            .map(|deployer| RegistryDeployerRhai::new(deployer))
            .map_err(|e| to_rhai_err(e))
    }
}

/// Rhai wrapper for RegistryDeployer (result of deploy)
#[derive(Clone)]
pub struct RegistryDeployerRhai {
    deployer: crate::kubernetes::RegistryDeployer,
}

impl RegistryDeployerRhai {
    /// Create a new RegistryDeployerRhai wrapper
    pub fn new(deployer: crate::kubernetes::RegistryDeployer) -> Self {
        Self { deployer }
    }

    /// Get connection string
    pub fn connection_string(&self) -> String {
        self.deployer.connection_string()
    }

    /// Get external connection string
    pub fn external_connection_string(&self) -> Option<String> {
        self.deployer.external_connection_string()
    }

    /// Get image prefix
    pub fn image_prefix(&self) -> String {
        self.deployer.image_prefix()
    }

    /// Get external image prefix
    pub fn external_image_prefix(&self) -> Option<String> {
        self.deployer.external_image_prefix()
    }

    /// Get registry name
    pub fn name(&self) -> String {
        self.deployer.name().to_string()
    }

    /// Get namespace
    pub fn namespace(&self) -> String {
        self.deployer.namespace().to_string()
    }

    /// Get port
    pub fn port(&self) -> i64 {
        self.deployer.port() as i64
    }

    /// Get node port
    pub fn node_port(&self) -> i64 {
        self.deployer.node_port().unwrap_or(0) as i64
    }
}
