# Helper Logger Module for PowerShell Scripts
# Provides consistent logging functionality across all scripts
#
# Log File Management:
# - Log files are created with format: migration_YYYYMMDD_HHMMSS.log
# - If a log file from the same day already exists, it will be reused
# - New sessions are separated by clear dividers in the log file
# - Old log files (older than 7 days) are automatically cleaned up
# - This prevents multiple log files from being created during the same migration session

# Script-level variable to store the log file path for the current session
$script:CurrentLogFile = $null
$script:SharedLogFile = $null

function New-SharedLogFile {
    param(
        [Parameter(Mandatory=$true)]
        [string]$MigrationDirectory,
        
        [Parameter(Mandatory=$false)]
        [string]$LogFileName = $null
    )
    
    # Create logs directory if it doesn't exist
    $logDir = Join-Path $MigrationDirectory "logs"
    if (-not (Test-Path $logDir)) {
        New-Item -ItemType Directory -Path $logDir -Force | Out-Null
    }
    
    # If a specific log filename is provided, use it
    if (-not [string]::IsNullOrWhiteSpace($LogFileName)) {
        $script:SharedLogFile = Join-Path $logDir $LogFileName
        $script:CurrentLogFile = $script:SharedLogFile
        return $script:SharedLogFile
    }
    
    # Check for existing log files from today
    $today = Get-Date -Format "yyyyMMdd"
    $existingLogs = Get-ChildItem -Path $logDir -Filter "migration_${today}*.log" -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending
    
    if ($existingLogs.Count -gt 0) {
        # Use the most recent log file from today
        $script:SharedLogFile = $existingLogs[0].FullName
        $script:CurrentLogFile = $script:SharedLogFile
        
        # Add a separator to indicate a new session
        $sessionSeparator = "`n" + ("=" * 80) + "`n" + "[NEW SESSION STARTED: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')]" + "`n" + ("=" * 80)
        try {
            Add-Content -Path $script:SharedLogFile -Value $sessionSeparator -Encoding UTF8
        }
        catch {
            Write-Host "Warning: Could not add session separator to existing log file: $($_.Exception.Message)" -ForegroundColor Yellow
        }
        
        return $script:SharedLogFile
    }
    
    $LogFileName = "migration_$global:Timestamp.log"
    
    # Set the shared log file path
    $script:SharedLogFile = Join-Path $logDir $LogFileName
    
    # Also set the current log file to the shared one
    $script:CurrentLogFile = $script:SharedLogFile
    
    return $script:SharedLogFile
}

function Write-HelperLog {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Message,
        
        [Parameter(Mandatory=$false)]
        [ValidateSet("Info", "Warning", "Error", "Success")]
        [string]$Level = "Info",
        
        [Parameter(Mandatory=$false)]
        [string]$LogPrefix = "Script",
        
        [Parameter(Mandatory=$false)]
        [string]$MigrationDirectory
    )
    
    # Use shared log file if available, otherwise check for existing logs from today
    if ($null -eq $script:SharedLogFile) {
        # Create logs directory if it doesn't exist
        $logDir = Join-Path $MigrationDirectory "logs"
        if (-not (Test-Path $logDir)) {
            New-Item -ItemType Directory -Path $logDir -Force | Out-Null
        }
        
        # Check for existing log files from today
        if ($null -eq $script:CurrentLogFile) {
            $today = Get-Date -Format "yyyyMMdd"
            $existingLogs = Get-ChildItem -Path $logDir -Filter "migration_${today}*.log" -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending
            
            if ($existingLogs.Count -gt 0) {
                # Use the most recent log file from today
                $script:CurrentLogFile = $existingLogs[0].FullName
            } else {
                $script:CurrentLogFile = Join-Path $logDir "migration_$global:Timestamp.log"
            }
        }
    } else {
        # Use the shared log file
        $script:CurrentLogFile = $script:SharedLogFile
    }
    
    # Clean up multi-line messages by joining them into a single line
    $cleanMessage = $Message -replace "`r`n", " " -replace "`n", " " -replace "`r", " " -replace '\s+', ' '
    
    # Format the log message for file logging
    $logTimestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $formattedMessage = "[$logTimestamp] [$LogPrefix] [$Level] $cleanMessage"
    
    # Write to console with appropriate color and UI formatting
    switch ($Level) {
        "Info" { 
            Write-Host "[$logTimestamp]  [INFO] $Message" -ForegroundColor White 
        }
        "Warning" { 
            Write-Host "[$logTimestamp]  [WARNING] $Message" -ForegroundColor Yellow 
        }
        "Error" { 
            Write-Host "[$logTimestamp]  [ERROR] $Message" -ForegroundColor Red 
        }
        "Success" { 
            Write-Host ""
            Write-Host "[$logTimestamp]  [SUCCESS] $Message" -ForegroundColor Green 
            Write-Host ""
        }
    }
    
    # Write to log file
    try {
        Add-Content -Path $script:CurrentLogFile -Value $formattedMessage -Encoding UTF8
    }
    catch {
        Write-Host "Warning: Could not write to log file: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

# Export the functions
Export-ModuleMember -Function Write-HelperLog, New-SharedLogFile