#!/bin/bash

databaseListInstalledApp() 
{
    local app_name="$1"
    
    # Check if app name is provided
    if [ -z "$app_name" ]; then
        isNotice "App name is required. Usage: databaseListInstalledApp <app_name>"
    else
        # Check if sqlite3 is available
        if ! command -v sqlite3 &> /dev/null; then
            isNotice "sqlite3 command not found. Make sure it's installed."
        else
            # Check if database file is available
            if [ ! -f "$docker_dir/$db_file" ]; then
                isNotice "Database file not found. Make sure it's installed."
            else
                # Check if app exists and is installed
                local app_check=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT name FROM apps WHERE name = '$app_name' AND status = 1;")
                if [ -z "$app_check" ]; then
                    isNotice "App '$app_name' not found or not installed."
                else
                    local app_details=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT install_date, install_time FROM apps WHERE name = '$app_name';")
                    
                    printf "\e[33m📦 %s\e[0m (Installed: %s)\n" "$app_name" "$app_details"
                    
                    # Get all Docker services with IPs for this app
                    local docker_services=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT DISTINCT service_name, resource_value FROM network_resources WHERE app_name = '$app_name' AND resource_type = 'ip' AND status = 'active' ORDER BY service_name;" 2>/dev/null)
                    
                    if [[ -n "$docker_services" ]]; then
                        local service_count=0
                        local total_services=$(echo "$docker_services" | wc -l)
                        
                        while IFS='|' read -r docker_service_name docker_service_ip; do
                            ((service_count++))
                            
                            # Determine tree connector
                            local connector="├─"
                            if [[ $service_count -eq $total_services ]]; then
                                connector="└─"
                            fi
                            
                            printf "%s \e[94m🔌 Service:\e[0m %s (IP: %s)\n" "$connector" "$docker_service_name" "$docker_service_ip"
                            
                            # Get all ports for this Docker service
                            local service_ports=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT service_name, resource_value FROM network_resources WHERE app_name = '$app_name' AND resource_type = 'port' AND parent_service = '$docker_service_name' AND status = 'active' ORDER BY service_name;" 2>/dev/null)
                            
                            if [[ -n "$service_ports" ]]; then
                                local port_count=0
                                local total_ports=$(echo "$service_ports" | wc -l)
                                
                                while IFS='|' read -r port_service_name port_mapping; do
                                    ((port_count++))
                                    
                                    # Parse port mapping: external:internal:access:protocol
                                    local external_port=$(echo "$port_mapping" | cut -d':' -f1)
                                    local internal_port=$(echo "$port_mapping" | cut -d':' -f2)
                                    local access_type=$(echo "$port_mapping" | cut -d':' -f3)
                                    local protocol=$(echo "$port_mapping" | cut -d':' -f4)
                                    
                                    # Get URL accessibility from port_service_names array
                                    local url_accessible="false"
                                    local port_display_name="${port_service_name#$app_name\_}"
                                    
                                    for i in "${!port_service_names[@]}"; do
                                        if [[ "${port_service_names[$i]}" == "$port_display_name" && "${port_parent_services[$i]}" == "$docker_service_name" ]]; then
                                            url_accessible="${port_url_accessibles[$i]}"
                                            break
                                        fi
                                    done
                                    
                                    # Determine port connector
                                    local port_connector="│  ├─"
                                    if [[ $port_count -eq $total_ports ]]; then
                                        if [[ $service_count -eq $total_services ]]; then
                                            port_connector="   └─"
                                        else
                                            port_connector="│  └─"
                                        fi
                                    else
                                        if [[ $service_count -eq $total_services ]]; then
                                            port_connector="   ├─"
                                        fi
                                    fi
                                    
                                    # Display port with appropriate icon
                                    if [[ "$url_accessible" == "true" || "$access_type" == "public" ]]; then
                                        printf "%s \e[32m🌐\e[0m %s: \e[36m🔗 Ports: %s:%s (%s)\e[0m\n" "$port_connector" "$port_display_name" "$external_port" "$internal_port" "$access_type"
                                        
                                        # Display URL access for public or url_accessible ports
                                        if [[ "$url_accessible" == "true" || "$access_type" == "public" ]]; then
                                            # Display URL access
                                            local url_connector="   │  └─"
                                            if [[ $port_count -eq $total_ports ]]; then
                                                url_connector="      └─"
                                            fi
                                            
                                            # Check if Traefik is installed
                                            local traefik_installed=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT name FROM apps WHERE name = 'traefik' AND status = 1;" 2>/dev/null)

                                            # Per-port URL path: 10th column of the matching
                                            # CFG_<APP>_PORT_N row in the deployed config. Find the
                                            # row by matching service+name, then extract its url_path
                                            # (empty when the port has no web UI, e.g. DNS).
                                            local _port_url_path=""
                                            local _url_cfg="${containers_dir}/${app_name}/${app_name}.config"
                                            [[ ! -f "$_url_cfg" ]] && _url_cfg="${install_containers_dir}/${app_name}/${app_name}.config"
                                            if [[ -f "$_url_cfg" ]]; then
                                                while IFS='=' read -r _vn _vv || [[ -n "$_vn" ]]; do
                                                    [[ -z "$_vn" || "$_vn" =~ ^[[:space:]]*# ]] && continue
                                                    [[ "$_vn" =~ ^CFG_${app_name^^}_PORT_ ]] || continue
                                                    _vv="${_vv#\"}"; _vv="${_vv%\"}"
                                                    local _svc=$(echo "$_vv" | cut -d'|' -f1)
                                                    local _nm=$(echo  "$_vv" | cut -d'|' -f2)
                                                    if [[ "${_svc,,}" == "${docker_service_name,,}" \
                                                          && "${_nm,,}" == "${port_display_name,,}" ]]; then
                                                        local _fc=$(awk -F'|' '{print NF}' <<< "$_vv")
                                                        if [[ "$_fc" -ge 10 ]]; then
                                                            _port_url_path=$(echo "$_vv" | cut -d'|' -f10)
                                                        fi
                                                        break
                                                    fi
                                                done < "$_url_cfg"
                                            fi
                                            # Multi-button: comma-split the path. One External/Internal
                                            # line is printed per path so the install summary mirrors
                                            # the multiple "Open" buttons the WebUI Services tab renders.
                                            local _path_list
                                            IFS=',' read -ra _path_list <<< "$_port_url_path"
                                            [[ ${#_path_list[@]} -eq 0 ]] && _path_list=("")

                                            if [[ -z "$public_ip_v4" ]]; then
                                                public_ip_v4=$(dig +short myip.opendns.com @resolver1.opendns.com 2>/dev/null || echo "localhost")
                                            fi
                                            local public_ip=${public_ip_v4:-"localhost"}

                                            local _domain=""
                                            if [[ -n "$traefik_installed" ]]; then
                                                _domain=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT resource_value FROM options WHERE option = 'domain_${app_name^^}_DOMAIN';" 2>/dev/null)
                                            fi

                                            local _path_idx _p
                                            for _path_idx in "${!_path_list[@]}"; do
                                                _p="${_path_list[$_path_idx]}"
                                                if [[ -n "$_p" && "$_p" != /* ]]; then
                                                    _p="/$_p"
                                                fi

                                                if [[ -n "$traefik_installed" ]]; then
                                                    if [[ -n "$_domain" ]]; then
                                                        printf "%s \e[32m🌐 External:\e[0m https://${app_name}.${_domain}${_p}\n" "$url_connector"
                                                    else
                                                        printf "%s \e[32m🌐 External:\e[0m https://${app_name}.local${_p}\n" "$url_connector"
                                                    fi
                                                else
                                                    printf "%s \e[32m🌐 External:\e[0m http://${public_ip}:${external_port}${_p}\n" "$url_connector"
                                                fi

                                                # Always show internal access for each path.
                                                if [[ $port_count -eq $total_ports ]]; then
                                                    printf "      └─ \e[90m🔗 Internal:\e[0m http://${docker_service_ip}:${internal_port}${_p}\n"
                                                else
                                                    printf "   │  └─ \e[90m🔗 Internal:\e[0m http://${docker_service_ip}:${internal_port}${_p}\n"
                                                fi
                                            done
                                    else
                                        printf "%s \e[94m🔌\e[0m %s: \e[36m%s:%s\e[0m\n" "$port_connector" "$port_display_name" "$external_port" "$internal_port"
                                    fi
                                fi
                                done <<< "$service_ports"
                            fi
                        done <<< "$docker_services"
                    else
                        echo "└─ 🔌 No services found"
                    fi
                    echo ""
                fi
            fi
        fi
    fi
}
