#!/bin/bash

ipAllocation()
{
    local app_name="$1"
    local service_name="$2"

    if [[ -z "$app_name" ]]; then
        isError "App name is required for IP allocation"
        allocated_ip=""
    fi

    # Already-allocated IP for this app+service.
    local existing_ip
    existing_ip=$(sqlite3 "$docker_dir/$db_file" \
        "SELECT resource_value FROM network_resources \
         WHERE app_name='$app_name' AND resource_type='ip' \
           AND service_name='$service_name' AND status='active' LIMIT 1;" 2>/dev/null)

    if [[ -n "$existing_ip" ]]; then
        if [[ "$LIBREPORTAL_RESET_NETWORK" == "1" ]]; then
            ipFindAvailable
            if [[ -z "$available_ip" ]]; then
                isError "No available IP addresses in pool"
                allocated_ip="$existing_ip"
            fi
            sqlite3 "$docker_dir/$db_file" \
                "UPDATE network_resources \
                 SET resource_value='$available_ip', created_time=CURRENT_TIME \
                 WHERE app_name='$app_name' AND resource_type='ip' AND service_name='$service_name';" 2>/dev/null
            isNotice "Reset IP for $app_name/$service_name: $existing_ip → $available_ip"
            allocated_ip="$available_ip"
        else
            allocated_ip="$existing_ip"
        fi
    fi

    ipFindAvailable
    if [[ -z "$available_ip" ]]; then
        isError "No available IP addresses in pool"
        allocated_ip=""
    fi

    local sql="INSERT INTO network_resources (app_name, resource_type, resource_value, service_name, status, created_date, created_time) VALUES ('$app_name', 'ip', '$available_ip', '$service_name', 'active', CURRENT_DATE, CURRENT_TIME);"
    sqlite3 "$docker_dir/$db_file" "$sql" 2>/dev/null
    if [[ $? -eq 0 ]]; then
        isSuccessful "Allocated IP: $app_name/$service_name → $available_ip"
        allocated_ip="$available_ip"
    else
        isError "Failed to allocate IP for $app_name/$service_name"
        allocated_ip=""
    fi
}
