# Oracle and PostgreSQL Connection Information Collector Module
# This module provides functions to prompt for Oracle and PostgreSQL connection details and save them to axiummigration.properties
# Usage: Import-Module Helper-Get-Credentials.psm1; Get-DatabaseCredentials [-blank]
# Import the utilities module for logging and common functions
# This module will use the shared logger instance from Helper-Utilities

# Function to securely prompt for password
function Get-SecurePassword {
    param([string]$Prompt, [string]$DefaultValue = "")
    if ($DefaultValue -ne "") {
        $promptText = "$Prompt (current value exists - press Enter to keep)"
    } else {
        $promptText = $Prompt
    }
    $securePassword = Read-Host -Prompt $promptText -AsSecureString
    if ($securePassword.Length -eq 0 -and $DefaultValue -ne "") {
        return $DefaultValue
    }
    return [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword))
}

# Function to read properties file
function Read-PropertiesFile {
    param([string]$FilePath)
    $properties = @{}
    if (Test-Path $FilePath) {
        Get-Content $FilePath | ForEach-Object {
            if ($_ -match '^([^=]+)=(.*)$') {
                $properties[$matches[1]] = $matches[2]
            }
        }
    }
    return $properties
}

# Function to prompt with default value
function Read-HostWithDefault {
    param([string]$Prompt, [string]$DefaultValue = "", [bool]$Required = $false)
    if ($DefaultValue -ne "") {
        $promptText = "$Prompt (current: $DefaultValue)"
    } else {
        $promptText = $Prompt
    }
    if ($Required) {
        $promptText += " *"
    }
    $userInput = Read-Host -Prompt $promptText
    if ($userInput -eq "" -and $DefaultValue -ne "") {
        return $DefaultValue
    }
    return $userInput
}

# Function to prompt for required value
function Read-HostRequired {
    param([string]$Prompt, [string]$DefaultValue = "")
    do {
        $userInput = Read-HostWithDefault -Prompt $Prompt -DefaultValue $DefaultValue -Required $true
        if ($userInput -eq "") {
            Show-Error -Message "Required field - please enter a value." -LogPrefix "Credentials"
        }
    } while ($userInput -eq "")
    return $userInput
}

# Function to prompt for required secure password
function Read-HostRequiredSecure {
    param([string]$Prompt, [string]$DefaultValue = "")
    do {
        $userInput = Get-SecurePassword -Prompt $Prompt -DefaultValue $DefaultValue
        if ($userInput -eq "") {
            Show-Error -Message "Required field - please enter a value." -LogPrefix "Credentials"
        }
    } while ($userInput -eq "")
    return $userInput
}

# Main function to get database credentials
function Get-DatabaseCredentials {
    param(
        [switch]$ClearScreen = $false
    )
    
    # Clear the screen for a clean start only if requested and run directly
    if ($ClearScreen) {
        # Check if this module is being called from another script
        $callStack = Get-PSCallStack
        $isCalledFromAnotherScript = $callStack.Count -gt 1
        
        if (-not $isCalledFromAnotherScript) {
            Clear-Host
        }
    }
    
    # Display main header
    Show-Header "Database Migration Setup"
    Show-Info -Message "This script will help you configure your database connection settings." -LogPrefix "Credentials"
    Show-Info -Message "All connection information will be securely stored for the migration process." -LogPrefix "Credentials"
    
    $propertiesFile = Get-PropertiesFilePath
    # Read existing properties if file exists
    $existingProperties = Read-PropertiesFile -FilePath $propertiesFile
    
    # Check if file exists and show contents
    if (Test-Path $propertiesFile) {
        Show-Warning -Message "Existing configuration found:" -LogPrefix "Credentials"
        
        # Define all expected properties
        $expectedProperties = @(
            "ORACLE_TNS", "ORACLE_USER", "ORACLE_PASSWORD", "ORACLE_ADMIN_USER", "ORACLE_ADMIN_PASSWORD",
            "ORACLE_TNS_TYPE",
            "POSTGRES_SERVER", "POSTGRES_SERVER_PORT", "POSTGRES_ADMIN_USER", "POSTGRES_ADMIN_PASSWORD",
            "POSTGRES_SCHEMA", "POSTGRES_USER", "POSTGRES_USER_PASSWORD", "POSTGRES_DATABASE"
        )
        
        # Show existing properties and missing ones (redacting passwords)
        foreach ($prop in $expectedProperties) {
            if ($existingProperties.ContainsKey($prop)) {
                $value = $existingProperties[$prop]
                if ($value -eq "") {
                    Show-Error -Message "$prop=" -LogPrefix "Credentials"
                } else {
                    # Redact password fields
                    if ($prop -match "PASSWORD") {
                        Show-Info -Message "$prop=[REDACTED]" -LogPrefix "Credentials"
                    } else {
                        Show-Info -Message "$prop=$value" -LogPrefix "Credentials"
                    }
                }
            } else {
                Show-Error -Message "$prop=" -LogPrefix "Credentials"
            }
        }
        
        Write-Host ""
        $editChoice = Read-Host -Prompt "Update configuration? (y/n) (default: n)"
        if ($editChoice -notmatch "^(yes|y)$") {
            Show-Info -Message "Configuration unchanged." -LogPrefix "Credentials"
            return $true  # Changed from $false to $true
        }
    }
    
    Show-Section "Oracle Database Settings"
    Show-Info -Message "Enter your Oracle database connection information:" -LogPrefix "Credentials"
    
    $oracleTns = Read-HostRequired -Prompt "Oracle TNS/Connection String" -DefaultValue $existingProperties["ORACLE_TNS"]
    $oracleTnsTypeDefault = $existingProperties["ORACLE_TNS_TYPE"]
    if ($oracleTnsTypeDefault -eq "" -or $null -eq $oracleTnsTypeDefault) {
        $oracleTnsTypeDefault = "SID"
    }
    $oracleTnsType = Read-HostWithDefault -Prompt "Oracle Connection String Type (Service/SID)" -DefaultValue $oracleTnsTypeDefault
    if ($oracleTnsType -eq "") {
        $oracleTnsType = "SID"
    }

    $oracleUser = Read-HostRequired -Prompt "Oracle User Name" -DefaultValue $existingProperties["ORACLE_USER"]
    $oraclePassword = Read-HostRequiredSecure -Prompt "Oracle Password" -DefaultValue $existingProperties["ORACLE_PASSWORD"]
    $oracleAdminUser = Read-HostRequired -Prompt "Oracle Admin User" -DefaultValue $existingProperties["ORACLE_ADMIN_USER"]
    $oracleAdminPassword = Read-HostRequiredSecure -Prompt "Oracle Admin Password" -DefaultValue $existingProperties["ORACLE_ADMIN_PASSWORD"]
    
    Show-Section "PostgreSQL Database Settings"
    Show-Info -Message "Enter your PostgreSQL database connection information:" -LogPrefix "Credentials"
    
    $postgresServer = Read-HostRequired -Prompt "PostgreSQL Server" -DefaultValue $existingProperties["POSTGRES_SERVER"]
    $postgresServerPort = Read-HostRequired -Prompt "PostgreSQL Port" -DefaultValue $existingProperties["POSTGRES_SERVER_PORT"]
    $postgresAdminUser = Read-HostRequired -Prompt "PostgreSQL Admin User" -DefaultValue $existingProperties["POSTGRES_ADMIN_USER"]
    $postgresAdminPassword = Read-HostRequiredSecure -Prompt "PostgreSQL Admin Password" -DefaultValue $existingProperties["POSTGRES_ADMIN_PASSWORD"]
    
    Show-Section "Migration Settings"
    Show-Info -Message "Configure migration-specific settings (press Enter for suggested defaults):" -LogPrefix "Credentials"
    
    # Handle PostgreSQL schema with smart defaults
    $postgresSchemaDefault = $existingProperties["POSTGRES_SCHEMA"]
    if ($postgresSchemaDefault -eq "" -and $oracleUser -ne "") {
        $postgresSchemaDefault = $oracleUser.ToLower()
    }
    $postgresSchema = Read-HostWithDefault -Prompt "PostgreSQL Schema" -DefaultValue $postgresSchemaDefault

    # Check if all three PostgreSQL fields are empty to determine behavior
    $postgresUserExisting = $existingProperties["POSTGRES_USER"]
    $postgresUserPasswordExisting = $existingProperties["POSTGRES_USER_PASSWORD"]
    $postgresDatabaseExisting = $existingProperties["POSTGRES_DATABASE"]
    $allFieldsEmpty = (($postgresUserExisting -eq "" -or $null -eq $postgresUserExisting) -and 
                        ($postgresUserPasswordExisting -eq "" -or $null -eq $postgresUserPasswordExisting) -and 
                        ($postgresDatabaseExisting -eq "" -or $null -eq $postgresDatabaseExisting))
    
    # Only show default values information when all fields are empty
    if ($allFieldsEmpty) {
        Write-Host ""
        Show-Info -Message "PostgreSQL Default Values:" -LogPrefix "Credentials"
        Show-Info -Message ("  - User: If not specified, defaults to '{0}_user'" -f $postgresSchema) -LogPrefix "Credentials"
        Show-Info -Message ("  - User Password: If not specified, defaults to '{0}'" -f $postgresSchema) -LogPrefix "Credentials"
        Show-Info -Message ("  - Database: If not specified, defaults to '{0}_db'" -f $postgresSchema) -LogPrefix "Credentials"
        Write-Host ""
    }

    # Use Read-HostRequired if there are existing values, otherwise use Read-HostWithDefault
    if ($allFieldsEmpty) {
        $postgresUser = Read-HostWithDefault -Prompt "PostgreSQL User" -DefaultValue ($postgresSchema + "_user")
        # Ensure default is applied if user didn't enter anything
        
        if ($postgresUser -eq "" -and $postgresSchema -ne "") {
            $postgresUser = $postgresSchema + "_user"
        }
    } else {
        $postgresUser = Read-HostRequired -Prompt "PostgreSQL User" -DefaultValue $postgresUserExisting
    }

    # Use Read-HostRequired if there are existing values, otherwise use Read-HostWithDefault
    if ($allFieldsEmpty) {
        $postgresUserPassword = Read-HostRequiredSecure -Prompt "PostgreSQL User Password" -DefaultValue $postgresSchema
        if ($postgresUserPassword -eq "" -and $postgresSchema -ne "") {
            $postgresUserPassword = $postgresSchema
        }
    } else {
        $postgresUserPassword = Read-HostRequiredSecure -Prompt "PostgreSQL User Password" -DefaultValue $postgresUserPasswordExisting 
    }
    

    # Use Read-HostRequired if there are existing values, otherwise use Read-HostWithDefault
    if ($allFieldsEmpty) {
        $postgresDatabase = Read-HostWithDefault -Prompt "PostgreSQL Database" -DefaultValue ($postgresSchema + "_db")
        # Ensure default is applied if user didn't enter anything
        if ($postgresDatabase -eq "" -and $postgresSchema -ne "") {
            $postgresDatabase = $postgresSchema + "_db"
        }
    } else {
        $postgresDatabase = Read-HostRequired -Prompt "PostgreSQL Database" -DefaultValue $postgresDatabaseExisting
    }

    # Create the properties file content
    $propertiesContent = @"
ORACLE_TNS=$oracleTns
ORACLE_TNS_TYPE=$oracleTnsType
ORACLE_USER=$oracleUser
ORACLE_PASSWORD=$oraclePassword
ORACLE_ADMIN_USER=$oracleAdminUser
ORACLE_ADMIN_PASSWORD=$oracleAdminPassword
POSTGRES_SERVER=$postgresServer
POSTGRES_SERVER_PORT=$postgresServerPort
POSTGRES_ADMIN_USER=$postgresAdminUser
POSTGRES_ADMIN_PASSWORD=$postgresAdminPassword
POSTGRES_SCHEMA=$postgresSchema
POSTGRES_USER=$postgresUser
POSTGRES_USER_PASSWORD=$postgresUserPassword
POSTGRES_DATABASE=$postgresDatabase
MAX_TABLE_IMPORT=100
"@

    # Write to axiummigration.properties file
    try {
        $propertiesContent | Out-File -FilePath $propertiesFile -Encoding UTF8
        Show-Success -Message "Configuration saved to: $propertiesFile" -LogPrefix "Credentials"

        $encryptPlainTextPasswords = Convert-PlaintextPasswords -PropertiesFilePath $propertiesFile -ShowWarnings $false

        return $encryptPlainTextPasswords
    } catch {
        Show-Error -Message "Error creating configuration file: $($_.Exception.Message)" -LogPrefix "Credentials"
        return $false
    }
}

# Export the functions
Export-ModuleMember -Function Get-DatabaseCredentials