#!/bin/bash

# Store service-to-port mapping with safe update logic
portStoreMapping()
{
    local app_name="$1"
    local service_name="$2"
    local port_mapping="$3"  # e.g., "443:public:tcp" or "3000:private:tcp"
    local parent_service="$4"  # parent Docker service (optional)
    
    # Check if ports already exist for this app/service
    local existing=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT resource_value FROM network_resources WHERE app_name='$app_name' AND resource_type='port' AND service_name='$service_name' AND status='active';" 2>/dev/null)
    
    if [[ -n "$existing" ]]; then
        # UPDATE existing ports
        if [[ -n "$parent_service" ]]; then
            runInstallOp sqlite3 "$docker_dir/$db_file" "UPDATE network_resources SET resource_value='$port_mapping', parent_service='$parent_service', created_time=CURRENT_TIME WHERE app_name='$app_name' AND resource_type='port' AND service_name='$service_name';" 2>/dev/null
        else
            runInstallOp sqlite3 "$docker_dir/$db_file" "UPDATE network_resources SET resource_value='$port_mapping', created_time=CURRENT_TIME WHERE app_name='$app_name' AND resource_type='port' AND service_name='$service_name';" 2>/dev/null
        fi
        isNotice "Updated ports for $app_name/$service_name"
        #isNotice "Updated ports for $app_name/$service_name: $existing → $port_mapping"
    else
        # INSERT new ports
        if [[ -n "$parent_service" ]]; then
            runInstallOp sqlite3 "$docker_dir/$db_file" "INSERT INTO network_resources (app_name, resource_type, resource_value, service_name, parent_service, status, created_date, created_time) VALUES ('$app_name', 'port', '$port_mapping', '$service_name', '$parent_service', 'active', CURRENT_DATE, CURRENT_TIME);" 2>/dev/null
        else
            runInstallOp sqlite3 "$docker_dir/$db_file" "INSERT INTO network_resources (app_name, resource_type, resource_value, service_name, status, created_date, created_time) VALUES ('$app_name', 'port', '$port_mapping', '$service_name', 'active', CURRENT_DATE, CURRENT_TIME);" 2>/dev/null
        fi
        isSuccessful "Allocated port: $port_mapping"
    fi
}
