#!/bin/bash

dockerRemoveAppImages()
{
    local app_name="$1"

    if [[ -z "$app_name" ]]; then
        isNotice "No app name provided. Unable to remove Docker images."
        return
    fi

    isNotice "Removing Docker images for '$app_name'. Please wait..."

    local compose_dir="$containers_dir$app_name"
    local compose_file="$compose_dir/docker-compose.yml"
    local compose_images=""

    if [[ -f "$compose_file" ]]; then
        if [[ $CFG_DOCKER_INSTALL_TYPE == "rootless" ]]; then
            compose_images=$(dockerCommandRunInstallUser "cd $compose_dir && docker compose config --images" 2>/dev/null)
        elif [[ $CFG_DOCKER_INSTALL_TYPE == "rooted" ]]; then
            compose_images=$(cd "$compose_dir" && docker compose config --images 2>/dev/null)
        fi
    fi

    local matched_images=$(dockerCommandRun "docker images --format '{{.Repository}}:{{.Tag}}' | grep -E '(^|/)${app_name}(-|_|:|$)'" 2>/dev/null)

    local all_images=$(printf "%s\n%s\n" "$compose_images" "$matched_images" | sort -u | grep -v '^$' | grep -v '<none>')

    if [[ -z "$all_images" ]]; then
        isNotice "No Docker images found for '$app_name'."
        return
    fi

    while IFS= read -r image; do
        local result=$(dockerCommandRun "docker rmi -f '$image'" >/dev/null 2>&1)
        checkSuccess "Removed Docker image '$image'"
    done <<< "$all_images"
}
