#!/bin/bash

# Take an app's containers down + remove them. Two paths run in order:
#
#   1. `docker compose down -v --remove-orphans` from the app dir. Best
#      path — clean shutdown, named volumes pruned, orphans swept. Only
#      runs when the compose file is still on disk.
#
#   2. Name-based fallback (`dockerRemoveApp`): `docker ps -aqf name=$app`
#      → stop + rm. Always runs, even when compose down succeeded, to
#      catch containers compose wouldn't pick up — renamed/relabelled
#      ones, leftovers from a previously-failed uninstall, and the case
#      the user flagged: app dir already gone, compose step skipped,
#      containers were still running.
dockerComposeDownRemove()
{
    local app_name="$1"

    if [[ -z "$app_name" ]]; then
        isError "No app_name provided, unable to continue..."
        return 1
    fi

    if [[ -d "$containers_dir$app_name" ]]; then
        isNotice "Shutting down & removing all $app_name container data"
        if [[ "$CFG_DOCKER_INSTALL_TYPE" == "rootless" ]]; then
            dockerCommandRunInstallUser "cd $containers_dir$app_name && docker compose down -v --remove-orphans" >/dev/null 2>&1
        else
            (cd "$containers_dir$app_name" && docker compose down -v --remove-orphans) >/dev/null 2>&1
        fi
    else
        isNotice "App directory '$app_name' not found — falling back to name-based container cleanup."
    fi

    dockerRemoveApp "$app_name"
}
