# Database Upgrade Module
# This module provides functions to run database upgrade using AxiumDatabaseUpgrade
# Usage: Import-Module Helper-Run-Database-Upgrade.psm1; Start-DatabaseUpgrade
# Import the utilities module for logging and common functions
# Import the AxiumDatabaseUpgrade helper module for specific functions

# Import the AxiumDatabaseUpgrade helper module
$axiumDbUpgradePath = Get-HelperScriptPath "Helper-AxiumDatabaseUpgrade.psm1"
if (Test-Path $axiumDbUpgradePath) {
    Import-Module $axiumDbUpgradePath -Force
}

# Function to execute psql command
function Invoke-PostgresCommand {
    param(
        [string]$Command,
        [hashtable]$Properties,
        [string]$MigrationDirectory
    )
    
    # Set the PGPASSWORD environment variable to avoid password prompt
    $env:PGPASSWORD = $Properties['POSTGRES_USER_PASSWORD']
   
    # Escape the command properly to preserve quotes around column names
    $escapedCommand = $Command -replace '"', '""'
    $psqlCmd = "psql -U $($Properties['POSTGRES_USER']) -h $($Properties['POSTGRES_SERVER']) -p $($Properties['POSTGRES_SERVER_PORT']) -d $($Properties['POSTGRES_DATABASE']) -t -A -c `"$escapedCommand`""
    
    Show-Info -Message "Executing psql command: $psqlCmd" -LogPrefix "DatabaseUpgrade"
    
    try {
        $result = & cmd /c $psqlCmd 2>&1
        if ($LASTEXITCODE -eq 0) {
            Show-Success -Message "psql command executed successfully" -LogPrefix "DatabaseUpgrade"
            return $result
        } else {
            Show-Error -Message "psql command failed with exit code: $LASTEXITCODE" -LogPrefix "DatabaseUpgrade"
            Show-Error -Message "Command output: $result" -LogPrefix "DatabaseUpgrade"
            return $null
        }
    } catch {
        Show-Error -Message "Failed to execute psql command: $($_.Exception.Message)" -LogPrefix "DatabaseUpgrade"
        return $null
    }
}

# Function to check if AxiumDatabaseUpgrade exists
function Test-AxiumDatabaseUpgrade {    
    # Use utility function to get the path
    $axiumUpgradePath = Get-AxiumUpgradePath
    
    if (-not (Test-Path $axiumUpgradePath)) {
        Show-Error -Message "AxiumDatabaseUpgrade.exe not found at: $axiumUpgradePath" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "Please ensure AxiumDatabaseUpgrade is installed in the expected location." -LogPrefix "DatabaseUpgrade"
        return $false
    }
    Show-Success -Message "AxiumDatabaseUpgrade.exe found at: $axiumUpgradePath" -LogPrefix "DatabaseUpgrade"
    return $true
}

# Function to check and update appsettings.json
function Set-AppSettings {
    param(
        [string]$ActiveEngine = "EnterpriseDB"
    )
    
    # Use utility function to get the path
    $appSettingsDirectory = Get-AppSettingsPath
    $appSettingsPath = Join-Path $appSettingsDirectory "appsettings.json"
    
    # Create directory if it doesn't exist
    if (-not (Test-Path $appSettingsDirectory)) {
        Show-Info -Message "Creating appsettings directory: $appSettingsDirectory" -LogPrefix "DatabaseUpgrade"
        New-Item -ItemType Directory -Path $appSettingsDirectory -Force | Out-Null
    }
    
    # Create appsettings.json if it doesn't exist
    if (-not (Test-Path $appSettingsPath)) {
        Show-Info -Message "Creating appsettings.json at: $appSettingsPath" -LogPrefix "DatabaseUpgrade"
        
        # Create default appsettings.json structure with both engines
        $defaultAppSettings = @{
            DataLayer = @{
                ActiveEngine = $ActiveEngine
                ConnectionDictionary = @{}
                DatabaseEngines = @(
                    @{
                        Name = "EnterpriseDB"
                        Id = "EnterpriseDB_Libpq_Sync"
                    },
                    @{
                        Name = "Oracle"
                        Id = "Oracle_ODP_Sync"
                    }
                )
            }
        }
        
        $defaultAppSettings | ConvertTo-Json -Depth 10 | Set-Content $appSettingsPath
        Show-Success -Message "Created default appsettings.json with $ActiveEngine configuration" -LogPrefix "DatabaseUpgrade"
        return $true
    }
    
    Show-Info -Message "Checking appsettings.json configuration..." -LogPrefix "DatabaseUpgrade"
    
    try {
        $appSettings = Get-Content $appSettingsPath -Raw | ConvertFrom-Json
        
        $needsUpdate = $false
        
        # Check if DataLayer.ActiveEngine is set correctly
        if ($appSettings.DataLayer.ActiveEngine -ne $ActiveEngine) {
            Show-Info -Message "Updating ActiveEngine from '$($appSettings.DataLayer.ActiveEngine)' to '$ActiveEngine'" -LogPrefix "DatabaseUpgrade"
            $appSettings.DataLayer.ActiveEngine = $ActiveEngine
            $needsUpdate = $true
        }
        
        # Ensure ConnectionDictionary exists and is properly structured
        if (-not $appSettings.DataLayer.ConnectionDictionary) {
            Show-Info -Message "Adding ConnectionDictionary to DataLayer" -LogPrefix "DatabaseUpgrade"
            $appSettings.DataLayer.ConnectionDictionary = @{}
            $needsUpdate = $true
        }
        
        # Check and update DatabaseEngines array to include both engines
        $enterpriseDbEngine = $appSettings.DataLayer.DatabaseEngines | Where-Object { $_.Name -eq "EnterpriseDB" }
        $oracleEngine = $appSettings.DataLayer.DatabaseEngines | Where-Object { $_.Name -eq "Oracle" }
        
        # Ensure EnterpriseDB engine exists
        if (-not $enterpriseDbEngine) {
            Show-Info -Message "Adding EnterpriseDB engine to DatabaseEngines array" -LogPrefix "DatabaseUpgrade"
            $appSettings.DataLayer.DatabaseEngines += @{
                Name = "EnterpriseDB"
                Id = "EnterpriseDB_Libpq_Sync"
            }
            $needsUpdate = $true
        } else {
            # Update EnterpriseDB engine if needed
            if ($enterpriseDbEngine.Id -ne "EnterpriseDB_Libpq_Sync") {
                Show-Info -Message "Updating EnterpriseDB engine Id to 'EnterpriseDB_Libpq_Sync'" -LogPrefix "DatabaseUpgrade"
                $enterpriseDbEngine.Id = "EnterpriseDB_Libpq_Sync"
                $needsUpdate = $true
            }
        }
        
        # Ensure Oracle engine exists
        if (-not $oracleEngine) {
            Show-Info -Message "Adding Oracle engine to DatabaseEngines array" -LogPrefix "DatabaseUpgrade"
            $appSettings.DataLayer.DatabaseEngines += @{
                Name = "Oracle"
                Id = "Oracle_ODP_Sync"
            }
            $needsUpdate = $true
        } else {
            # Update Oracle engine if needed
            if ($oracleEngine.Id -ne "Oracle_ODP_Sync") {
                Show-Info -Message "Updating Oracle engine Id to 'Oracle_ODP_Sync'" -LogPrefix "DatabaseUpgrade"
                $oracleEngine.Id = "Oracle_ODP_Sync"
                $needsUpdate = $true
            }
        }
        
        if ($needsUpdate) {
            $appSettings | ConvertTo-Json -Depth 10 | Set-Content $appSettingsPath
            Show-Success -Message "appsettings.json updated successfully" -LogPrefix "DatabaseUpgrade"
        } else {
            Show-Info -Message "appsettings.json already has correct configuration" -LogPrefix "DatabaseUpgrade"
        }
        
        return $true
    } catch {
        Show-Error -Message "Failed to update appsettings.json: $($_.Exception.Message)" -LogPrefix "DatabaseUpgrade"
        return $false
    }
}

# Function to execute AxiumDatabaseUpgrade with real-time output
function Invoke-AxiumDatabaseUpgradeWithRealTimeOutput {
    param(
        [string]$AxiumUpgradePath,
        [string[]]$Arguments,
        [string]$WorkingDirectory,
        [string]$ProcessName = "AxiumDatabaseUpgrade"
    )
    
    if (-not (Test-Path $AxiumUpgradePath)) {
        Show-Error -Message "$ProcessName.exe not found at: $AxiumUpgradePath" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    

    Show-Info -Message "Executing $ProcessName command" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "Working directory: $WorkingDirectory" -LogPrefix "DatabaseUpgrade"

    try {
        Push-Location $WorkingDirectory
        Show-Info -Message "Starting $ProcessName execution with real-time output..." -LogPrefix "DatabaseUpgrade"
        
        # Create process start info for real-time output
        $processInfo = New-Object System.Diagnostics.ProcessStartInfo
        $processInfo.FileName = $AxiumUpgradePath
        $processInfo.Arguments = $Arguments -join " "
        $processInfo.WorkingDirectory = $WorkingDirectory
        $processInfo.UseShellExecute = $false
        $processInfo.RedirectStandardOutput = $true
        $processInfo.RedirectStandardError = $true
        $processInfo.CreateNoWindow = $false
        
        # Create and start the process
        $process = New-Object System.Diagnostics.Process
        $process.StartInfo = $processInfo
        
        # Use a simpler approach with direct command execution and real-time output
        $outputBuilder = New-Object System.Text.StringBuilder
        $errorOutputBuilder = New-Object System.Text.StringBuilder
        
        # Execute the command with real-time output processing
        # Use the call operator (&) to properly handle paths with spaces
        $exitCode = 0
        try {
            & $AxiumUpgradePath $Arguments 2>&1 | ForEach-Object {
                $line = $_
                if ($line -match "^ERROR|^FATAL|^Exception") {
                    $errorOutputBuilder.AppendLine($line) | Out-Null
                    Write-Host "Error: $line" -ForegroundColor Red
                } else {
                    $outputBuilder.AppendLine($line) | Out-Null
                    Write-Host "$line" -ForegroundColor Cyan
                }
            }
            $exitCode = $LASTEXITCODE
        } catch {
            $exitCode = 1
            $errorMessage = $_.Exception.Message
            $errorOutputBuilder.AppendLine($errorMessage) | Out-Null
            Show-Error -Message "Failed to execute command: $errorMessage" -LogPrefix "DatabaseUpgrade"
        }
        
        $errorOutput = $errorOutputBuilder.ToString()
        
        Pop-Location
        
        if ($exitCode -eq 0) {
            Show-Success -Message "$ProcessName command executed successfully" -LogPrefix "DatabaseUpgrade"
            return $true
        } else {
            Show-Error -Message "$ProcessName command failed with exit code: $exitCode" -LogPrefix "DatabaseUpgrade"
            if ($errorOutput) {
                Show-Error -Message "Error output: $errorOutput" -LogPrefix "DatabaseUpgrade"
            }
            return $false
        }
    } catch {
        Pop-Location
        Show-Error -Message "Failed to execute $ProcessName command: $($_.Exception.Message)" -LogPrefix "DatabaseUpgrade"
        return $false
    }
}

# Function to execute AxiumDatabaseUpgrade command for PostgreSQL
function Invoke-AxiumDatabasePostgresUpgrade {
    param(
        [hashtable]$Properties
    )
    
    # Use utility function to get the path
    $axiumUpgradePath = Get-AxiumUpgradePath
    $workingDirectory = Split-Path $axiumUpgradePath
    
    # Build the arguments array for Start-Process
    $arguments = @(
        "upgradepass",
        $Properties['POSTGRES_SERVER'],
        $Properties['POSTGRES_USER'],
        $Properties['POSTGRES_USER_PASSWORD'],
        "/DbEngine=ENTERPRISEDB",
        "/DbName=$($Properties['POSTGRES_DATABASE'])",
        "/Port=$($Properties['POSTGRES_SERVER_PORT'])",
        "/dev"
    )
    
    return Invoke-AxiumDatabaseUpgradeWithRealTimeOutput -AxiumUpgradePath $axiumUpgradePath -Arguments $arguments -WorkingDirectory $workingDirectory -ProcessName "AxiumDatabaseUpgrade"
}

# Function to execute AxiumDatabaseUpgrade command for Oracle
function Invoke-OracleAxiumDatabaseUpgrade {
    param(
        [hashtable]$Properties
    )
    
    # Use utility function to get the path
    $axiumUpgradePath = Get-AxiumUpgradePath
    $workingDirectory = Split-Path $axiumUpgradePath
    
    # Build the arguments array for Start-Process
    $arguments = @(
        "upgradepass",
        $Properties['ORACLE_TNS'],
        $Properties['ORACLE_USER'],
        $Properties['ORACLE_PASSWORD'],
        "/dev"
    )
    
    return Invoke-AxiumDatabaseUpgradeWithRealTimeOutput -AxiumUpgradePath $axiumUpgradePath -Arguments $arguments -WorkingDirectory $workingDirectory -ProcessName "AxiumDatabaseUpgrade Oracle"
}

# Main function to run database upgrade for PostgreSQL
function Start-PostgresDatabaseUpgradewithPracticeDowngrade {
    param(
        [hashtable]$Properties,
        [string]$MigrationDirectory
    )
    
    Show-Header "Database Upgrade"
    Show-Info -Message "This step will check the database version and run the database upgrade if needed." -LogPrefix "DatabaseUpgrade"
    
    # Check if AxiumDatabaseUpgrade exists before starting
    Show-Section "Checking AxiumDatabaseUpgrade Availability"
    if (-not (Test-AxiumDatabaseUpgrade)) {
        Show-Error -Message "AxiumDatabaseUpgrade is required but not found. Please ensure it is installed before proceeding." -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Validate that properties are provided
    if ($null -eq $Properties) {
        Show-Error -Message "Properties parameter is required. Please provide the migration properties." -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Check if required properties are available
    $requiredProperties = @(
        "POSTGRES_USER", "POSTGRES_SERVER", "POSTGRES_SERVER_PORT", 
        "POSTGRES_DATABASE", "POSTGRES_USER_PASSWORD"
    )
    
    $missingProperties = @()
    foreach ($prop in $requiredProperties) {
        if (-not $Properties.ContainsKey($prop) -or $Properties[$prop] -eq "") {
            $missingProperties += $prop
        }
    }
    
    if ($missingProperties.Count -gt 0) {
        Show-Error -Message "Missing required properties: $($missingProperties -join ', ')" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "Please run Step 1 first to configure all required properties." -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Ask user if they want to run database upgrade
    Show-Section "Database Upgrade Confirmation"
    Show-Info -Message "" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "  Database Configuration:" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "  - PostgreSQL User: $($Properties['POSTGRES_USER'])" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "  - PostgreSQL Server: $($Properties['POSTGRES_SERVER']):$($Properties['POSTGRES_SERVER_PORT'])" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "  - PostgreSQL Database: $($Properties['POSTGRES_DATABASE'])" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "" -LogPrefix "DatabaseUpgrade"
    
    # Proceed automatically without user confirmation
    Show-Info -Message "Proceeding with database upgrade..." -LogPrefix "DatabaseUpgrade"
    
    # Check current database version
    Show-Section "Checking Current Database Version"
    
    # First check if the practice table exists
    $tableCheckQuery = "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'practice')"
    Show-Info -Message "Checking if practice table exists..." -LogPrefix "DatabaseUpgrade"
    $tableExists = Invoke-PostgresCommand -Command $tableCheckQuery -Properties $Properties -MigrationDirectory $MigrationDirectory
    
    if ($null -eq $tableExists) {
        Show-Error -Message "Failed to check if practice table exists" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    if ($tableExists -match "f") {
        Show-Error -Message "Practice table does not exist in the database" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "This database may not be a valid Axium database or may not be properly initialized" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Check if Version column exists
    $columnCheckQuery = "SELECT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'practice' AND column_name = 'Version')"
    Show-Info "Checking if Version column exists..."
    $columnExists = Invoke-PostgresCommand -Command $columnCheckQuery -Properties $Properties -MigrationDirectory $MigrationDirectory
    
    if ($null -eq $columnExists) {
        Show-Error "Failed to check if Version column exists"
        return $false
    }
    
    if ($columnExists -match "f") {
        Show-Error "Version column does not exist in practice table"
        Show-Error "This database may not be a valid Axium database or may not be properly initialized"
        return $false
    }
    
    # Check if practice table has any rows
    $rowCountQuery = "SELECT COUNT(*) FROM practice"
    Show-Info "Checking if practice table has data..."
    $rowCount = Invoke-PostgresCommand -Command $rowCountQuery -Properties $Properties -MigrationDirectory $MigrationDirectory
    
    if ($null -eq $rowCount) {
        Show-Error -Message "Failed to check practice table row count" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    if ($rowCount -match "^0$") {
        Show-Error -Message "Practice table is empty" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "This database may not be a valid Axium database or may not be properly initialized" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    $versionQuery = 'SELECT "Version" FROM practice GROUP BY "Version" ORDER BY "Version" ASC'
    Show-Info -Message "Executing version query: $versionQuery"
    $versionResult = Invoke-PostgresCommand -Command $versionQuery -Properties $Properties -MigrationDirectory $MigrationDirectory
    
    if ($null -eq $versionResult -or $versionResult.Trim() -eq "") {
        Show-Info -Message "First version query returned no results, trying alternative query..." -MigrationDirectory $MigrationDirectory
        Show-Info -Message "First version query returned no results, trying alternative query..." -LogPrefix "DatabaseUpgrade"
        $versionQuery = 'SELECT "Version" FROM practice LIMIT 1'
        Show-Info -Message "Executing alternative version query: $versionQuery" -MigrationDirectory $MigrationDirectory
        Show-Info -Message "Executing alternative version query: $versionQuery" -LogPrefix "DatabaseUpgrade"
        $versionResult = Invoke-PostgresCommand -Command $versionQuery -Properties $Properties -MigrationDirectory $MigrationDirectory
        
        if ($null -eq $versionResult -or $versionResult.Trim() -eq "") {
            Show-Error -Message "Failed to retrieve database version from both queries" -MigrationDirectory $MigrationDirectory 
            Show-Error -Message "Failed to retrieve database version from both queries" -LogPrefix "DatabaseUpgrade"
            return $false
        }
    }
        
    # Parse the version result - try multiple approaches
    $currentVersion = $null
    
    # First try: split by newlines and get the first non-empty line
    $versionLines = $versionResult -split "`n" | Where-Object { $_.ToString().Trim() -ne "" }
    
    if ($versionLines.Count -gt 0) {
        $currentVersion = $versionLines[0].ToString().Trim()
    }
    
    # If that didn't work, try using the raw result directly
    if (-not $currentVersion -or $currentVersion.Length -lt 3) {
        $currentVersion = $versionResult.Trim()
    }
    
    if (-not $currentVersion) {
        Show-Error -Message "No version information found in database" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "Raw version result: $versionResult" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    
    # Remove any extra formatting that might be present
    $currentVersion = $currentVersion -replace '^\s*\(\s*', '' -replace '\s*\)\s*$', ''
    
    # Handle the case where the version might be wrapped in quotes
    $currentVersion = $currentVersion -replace '^''', '' -replace '''$', ''
    $currentVersion = $currentVersion -replace '^"', '' -replace '"$', ''
    
    # Validate that the version is a proper number format and convert to integer
    if ($currentVersion -match '^[0-9]+$') {
        $currentVersionInt = [int]$currentVersion
        Show-Info -Message "Current database version: $currentVersionInt" -LogPrefix "DatabaseUpgrade"
    } else {
        Show-Error -Message "Invalid database version format: '$currentVersion'" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "Expected a numeric version number" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "Raw version result: $versionResult" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Check if version is greater than 20250200 (numeric comparison)
    Show-Info -Message "Comparing version $currentVersionInt with 20250100" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "Version type: $($currentVersionInt.GetType().Name)" -LogPrefix "DatabaseUpgrade"
    
    if ($currentVersionInt -gt 20250100) {
        Show-Info -Message "Database version ($currentVersionInt) is greater than 20250100" -LogPrefix "DatabaseUpgrade"
        Show-Info -Message "Database will be downgraded to 2025.1" -LogPrefix "DatabaseUpgrade"
        
        $updateQuery = 'UPDATE PRACTICE SET "Version" = 20250100'
        $updateResult = Invoke-PostgresCommand -Command $updateQuery -Properties $Properties -MigrationDirectory $MigrationDirectory
        
        if ($null -eq $updateResult) {  
            Show-Error -Message "Failed to downgrade database version" -LogPrefix "DatabaseUpgrade"
            return $false
        }
        
        Show-Success -Message "Database version downgraded to 20250100" -LogPrefix "DatabaseUpgrade"
    } else {
        Show-Info -Message "Database version ($currentVersionInt) is not greater than 20250100" -LogPrefix "DatabaseUpgrade"
        Show-Info -Message "Database will be upgraded to the latest version" -LogPrefix "DatabaseUpgrade"
    }
    
    # Update appsettings.json
    Show-Section "Updating AppSettings Configuration"
            if (-not (Set-AppSettings -ActiveEngine "EnterpriseDB")) {
        return $false
    }
    
    # Run AxiumDatabaseUpgrade
    Show-Section "Running AxiumDatabaseUpgrade"
    if (-not (Invoke-AxiumDatabasePostgresUpgrade -Properties $Properties)) {
        Show-Error -Message "AxiumDatabaseUpgrade failed" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    Show-Success -Message "Database upgrade completed successfully!" -LogPrefix "DatabaseUpgrade"
    return $true
}

# Main function to run database upgrade for Oracle
function Start-OracleDatabaseUpgrade {
    param(
        [hashtable]$Properties
    )
    
    Show-Header "Oracle Database Upgrade"
    Show-Info -Message "This step will run the database upgrade for Oracle." -LogPrefix "DatabaseUpgrade"
    
    # Check if AxiumDatabaseUpgrade exists before starting
    Show-Section -Message "Checking AxiumDatabaseUpgrade Availability" -LogPrefix "DatabaseUpgrade"
    if (-not (Test-AxiumDatabaseUpgrade)) {
        Show-Error -Message "AxiumDatabaseUpgrade is required but not found. Please ensure it is installed before proceeding." -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Validate that properties are provided
    if ($null -eq $Properties) {
        Show-Error -Message "Properties parameter is required. Please provide the migration properties." -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Check if required Oracle properties are available
    $requiredProperties = @(
        "ORACLE_TNS", "ORACLE_USER", "ORACLE_PASSWORD"
    )
    
    $missingProperties = @()
    foreach ($prop in $requiredProperties) {
        if (-not $Properties.ContainsKey($prop) -or $Properties[$prop] -eq "") {
            $missingProperties += $prop
        }
    }
    
    if ($missingProperties.Count -gt 0) {
        Show-Error -Message "Missing required Oracle properties: $($missingProperties -join ', ')" -LogPrefix "DatabaseUpgrade"
        Show-Error -Message "Please run Step 1 first to configure all required Oracle properties." -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    # Show database configuration
    Show-Section "Oracle Database Upgrade Confirmation"
    Show-Info -Message "" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "  Oracle Database Configuration:" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "  - Oracle TNS: $($Properties['ORACLE_TNS'])" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "  - Oracle User: $($Properties['ORACLE_USER'])" -LogPrefix "DatabaseUpgrade"
    Show-Info -Message "" -LogPrefix "DatabaseUpgrade"
    
    # Proceed automatically without user confirmation
    Show-Info -Message "Proceeding with Oracle database upgrade..." -LogPrefix "DatabaseUpgrade"
    
    # Update appsettings.json for Oracle
    Show-Section "Updating AppSettings Configuration for Oracle"
            if (-not (Set-AppSettings -ActiveEngine "Oracle")) {
        return $false
    }
    
    # Run AxiumDatabaseUpgrade for Oracle
    Show-Section "Running AxiumDatabaseUpgrade for Oracle"
    if (-not (Invoke-OracleAxiumDatabaseUpgrade -Properties $Properties)) {
        Show-Error -Message "AxiumDatabaseUpgrade for Oracle failed" -LogPrefix "DatabaseUpgrade"
        return $false
    }
    
    Show-Success -Message "Oracle database upgrade completed successfully!" -LogPrefix "DatabaseUpgrade"
    return $true
}

# Export the functions
Export-ModuleMember -Function Start-PostgresDatabaseUpgradewithPracticeDowngrade, Start-OracleDatabaseUpgrade, Test-AxiumDatabaseUpgrade, Set-AppSettings, Invoke-AxiumDatabasePostgresUpgrade, Invoke-OracleAxiumDatabaseUpgrade, Invoke-PostgresCommand

