// File: /root/code/git.threefold.info/herocode/sal/src/virt/nerdctl/images.rs

use super::NerdctlError;
use super::execute_nerdctl_command;
use crate::process::CommandResult;
use herolib_core::text::path_fix;
use serde::{Deserialize, Serialize};

/// Represents a container image
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Image {
    /// Image ID
    pub id: String,
    /// Image repository
    pub repository: String,
    /// Image tag
    pub tag: String,
    /// Image size
    pub size: String,
    /// Creation timestamp
    pub created: String,
}

/// List images in local storage
pub fn images() -> Result<CommandResult, NerdctlError> {
    execute_nerdctl_command(&["images"])
}

/// Remove one or more images
///
/// # Arguments
///
/// * `image` - Image ID or name
pub fn image_remove(image: &str) -> Result<CommandResult, NerdctlError> {
    execute_nerdctl_command(&["rmi", image])
}

/// Push an image to a registry
///
/// # Arguments
///
/// * `image` - Image name
/// * `destination` - Destination registry URL
pub fn image_push(image: &str, destination: &str) -> Result<CommandResult, NerdctlError> {
    execute_nerdctl_command(&["push", image, destination])
}

/// Add an additional name to a local image
///
/// # Arguments
///
/// * `image` - Image ID or name
/// * `new_name` - New name for the image
pub fn image_tag(image: &str, new_name: &str) -> Result<CommandResult, NerdctlError> {
    execute_nerdctl_command(&["tag", image, new_name])
}

/// Pull an image from a registry
///
/// # Arguments
///
/// * `image` - Image name
pub fn image_pull(image: &str) -> Result<CommandResult, NerdctlError> {
    execute_nerdctl_command(&["pull", image])
}

/// Commit a container to an image
///
/// # Arguments
///
/// * `container` - Container ID or name
/// * `image_name` - New name for the image
pub fn image_commit(container: &str, image_name: &str) -> Result<CommandResult, NerdctlError> {
    execute_nerdctl_command(&["commit", container, image_name])
}

/// Build an image using a Dockerfile
///
/// # Arguments
///
/// * `tag` - Tag for the new image
/// * `context_path` - Path to the build context
pub fn image_build(tag: &str, context_path: &str) -> Result<CommandResult, NerdctlError> {
    let context_path = path_fix(context_path);
    execute_nerdctl_command(&["build", "-t", tag, &context_path])
}
