# Toolkit Properties Update Module
# This module provides functions to update C:\Program Files\edb\mtk\etc\toolkit.properties
# Usage: Import-Module Helper-Update-Toolkit-Properties.psm1; Update-ToolkitProperties

# Import the utilities module for logging and common functions
# This module will use the shared logger instance from Helper-Utilities

# Import the logger module for proper logging functionality
# Note: The logger module should already be imported by the calling script
# This is just a fallback in case it's not available

# Function to transform ORACLE_TNS format between SID and service formats
function Convert-OracleTns {
    param(
        [string]$OracleTns,
        [bool]$UseServiceFormat = $false
    )
    
    if ($UseServiceFormat) {
        # Convert to service format (host:port/service)
        # Example: host:port:sid -> host:port/service
        if ($OracleTns -match '(.+):([^:]+)$' -and $OracleTns -notmatch '/') {
            # Convert SID format (host:port:sid) to service format (host:port/service)
            $hostPort = $matches[1]
            $serviceName = $matches[2]
            return "$hostPort/$serviceName"
        } elseif ($OracleTns -match '(.+)/([^/]+)$') {
            # Already in service format
            return $OracleTns
        }
    } else {
        # Convert to SID format (host:port:service)
        # Example: host:port/service -> host:port:service
        if ($OracleTns -match '(.+)/([^/]+)$') {
            $hostPort = $matches[1]
            $serviceName = $matches[2]
            return "$hostPort`:$serviceName"
        }
    }
    
    # If no transformation needed, return as is
    return $OracleTns
}


# Function to create toolkit.properties content
function New-ToolkitPropertiesContent {
    param(
        [hashtable]$Properties,
        [bool]$UseServiceFormat = $false
    )
    
    # Transform ORACLE_TNS based on connection string type
    $transformedOracleTns = Convert-OracleTns -OracleTns $Properties["ORACLE_TNS"] -UseServiceFormat $UseServiceFormat
    
    # Get current timestamp for last updated
    $lastUpdated = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    
    # Create the toolkit.properties content
    $toolkitContent = @"
# EDB Migration Toolkit Properties
# Last Updated: $lastUpdated
# Generated by axiUm Database Migration Script

SRC_DB_URL=jdbc:oracle:thin:@$transformedOracleTns
SRC_DB_USER=$($Properties["ORACLE_USER"])
SRC_DB_PASSWORD=$($Properties["ORACLE_PASSWORD"])
TARGET_DB_URL=jdbc:edb://$($Properties["POSTGRES_SERVER"]):$($Properties["POSTGRES_SERVER_PORT"])/$($Properties["POSTGRES_DATABASE"])
TARGET_DB_USER=$($Properties["POSTGRES_USER"])
TARGET_DB_PASSWORD=$($Properties["POSTGRES_USER_PASSWORD"])
"@
    
    return $toolkitContent
}

# Main function to update toolkit.properties
function Set-ToolkitProperties {
    param(
        [hashtable]$Properties
    )

    Show-Header "Toolkit Properties Update"
    Show-Info -Message "This step will update the EDB Migration Toolkit properties file." -LogPrefix "ToolkitProperties"
    Show-Info -Message "The file will be created or updated at: C:\Program Files\edb\mtk\etc\toolkit.properties" -LogPrefix "ToolkitProperties"

    # Validate that properties are provided
    if ($null -eq $Properties) {
        Show-Error -Message "Properties parameter is required. Please provide the migration properties." -LogPrefix "ToolkitProperties"
        return $false
    }

    # Decrypt password properties before validation and use
    $decryptedProperties = Unprotect-Properties -Properties $Properties

    # Check if required properties are available
    $requiredProperties = @(
        "ORACLE_TNS", "ORACLE_USER", "ORACLE_PASSWORD",
        "POSTGRES_SERVER", "POSTGRES_SERVER_PORT", "POSTGRES_DATABASE",
        "POSTGRES_USER", "POSTGRES_USER_PASSWORD"
    )

    $missingProperties = @()
    foreach ($prop in $requiredProperties) {
        if (-not $decryptedProperties.ContainsKey($prop) -or $decryptedProperties[$prop] -eq "") {
            $missingProperties += $prop
        }
    }

    if ($missingProperties.Count -gt 0) {
        Show-Error -Message "Missing required properties: $($missingProperties -join ', ')" -LogPrefix "ToolkitProperties"
        Show-Error -Message "Please run Step 1 first to configure all required properties." -LogPrefix "ToolkitProperties"
        return $false
    }
    
    # Define toolkit.properties path
    $toolkitPropertiesPath = "C:\Program Files\edb\mtk\etc\toolkit.properties"
    
    # Check if EDB MTK directory exists
    $mtkDir = Split-Path $toolkitPropertiesPath -Parent
    if (-not (Test-Path $mtkDir)) {
        Show-Warning -Message "EDB MTK directory not found: $mtkDir" -LogPrefix "ToolkitProperties" 
        Show-Warning -Message "Please ensure EDB Migration Toolkit is installed." -LogPrefix "ToolkitProperties" 
        return $false
    }

    # Read ORACLE_TNS_TYPE type from properties
    $useServiceFormat = $false
    $oracleConnectionStringType = $decryptedProperties["ORACLE_TNS_TYPE"]
    
    if ($oracleConnectionStringType -and $oracleConnectionStringType -eq "Service") {
        $useServiceFormat = $true
        Show-Info -Message "Using service connection string format (from OORACLE_TNS_TYPE property)." -LogPrefix "ToolkitProperties"
    } else {
        Show-Info -Message "Using SID connection string format (default)." -LogPrefix "ToolkitProperties"
        if ($oracleConnectionStringType -and $oracleConnectionStringType -ne "SID") {
            Show-Warning -Message "ORACLE_TNS_TYPE property has unexpected value: '$oracleConnectionStringType'. Expected 'Service' or 'SID'. Using SID format." -LogPrefix "ToolkitProperties"
        }
    }

    # Create new toolkit.properties content
    Show-Info -Message "Creating toolkit.properties content..." -LogPrefix "ToolkitProperties"
    $toolkitContent = New-ToolkitPropertiesContent -Properties $decryptedProperties -UseServiceFormat $useServiceFormat
    
    # Write the file
    try {
        $toolkitContent | Out-File -FilePath $toolkitPropertiesPath -Encoding UTF8 -Force
        Show-Success -Message "Toolkit properties file updated successfully!" -LogPrefix "ToolkitProperties" 
        Show-Info -Message "File location: $toolkitPropertiesPath" -LogPrefix "ToolkitProperties" 
        return $true
    } catch {
        Show-Error -Message "Failed to write toolkit.properties file: $($_.Exception.Message)" -LogPrefix "ToolkitProperties" 
        return $false
    }
}

# Export the functions
Export-ModuleMember -Function Set-ToolkitProperties, Convert-OracleTns, New-ToolkitPropertiesContent 