# Script-level parameters and cmdlet binding to support -Verbose and common parameters
[CmdletBinding()]
param (
    [switch]$Quiet
)

function Write-LogMessage {
    param (
        [string]$message,
        [ValidateSet('Info','Warning')] [string]$Level = 'Info'
    )

    if ($Quiet) { return }

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    if ($Level -eq 'Warning') {
        Write-Host "[$timestamp] WARNING: $message"
    }
    else {
        Write-Host "[$timestamp] $message"
    }
}

function Save-ElxInternals {
    param(
        [ValidateScript({ Test-Path $_ -PathType Leaf })][Parameter(Mandatory)]$ModulePath
    )

    if (-not $Quiet) {
        Write-Host "Switching to ELX Tools directory..."
    }

    $extractElxToolsScriptPath = Join-Path $PSScriptRoot "../tools/extract-elx/"
    Push-Location -StackName ElxTools $extractElxToolsScriptPath

    if (-not $Quiet) {
        Write-Host "Installing Node.js dependencies for the ELX Tools..."
    }

    # Install Node.js dependencies for the ELX Tools
    & npm install
    if ($LASTEXITCODE -ne 0) {
        Write-Error "npm install failed with exit code $LASTEXITCODE."
        exit 1
    }

    if (-not $Quiet) {
        Write-Host "Node.js dependencies installed successfully!" -ForegroundColor Cyan
        Write-Host "Executing ELX extraction..."
    }

    & node "extract-elx.js" $ModulePath --clean
    if ($LASTEXITCODE -ne 0) {
        Write-Error "ELX extraction failed with exit code $LASTEXITCODE."
        exit 1
    }

    if (-not $Quiet) {
        Write-Host "ELX extraction completed successfully!" -ForegroundColor Green
        Write-Host "Switching back to original directory..."
    }

    Pop-Location -StackName ElxTools
}

function Convert-UrlToElixAutocompleteFormat {
    param (
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][uri]$AbsoluteUrl
    )

    Write-LogMessage "Converting URL '$($AbsoluteUrl.Host)' to elixForms WS call format..."
    $domain = $AbsoluteUrl.Host -replace '-', '--' -replace '\.', '-'
    $path = $AbsoluteUrl.AbsolutePath.TrimStart('/') -replace '-', '--' -replace '/', '-'
    $url = "/eF/services/api/remote/$domain/$path/v1"

    # Preserve query parameter order using an ordered hashtable and URL-decode values
    $queryParams = [ordered]@{}
    $rawQuery = $AbsoluteUrl.Query.TrimStart('?')
    if ($rawQuery) {
        $rawQuery.Split('&') | ForEach-Object {
                if ($_ -ne '') {
                    $pair = $_ -split '=', 2
                    $key = $pair[0]
                    $value = if ($pair.Count -gt 1) { $pair[1] } else { '' }

                    if ($queryParams.Contains($key)) {
                        # Append duplicate values with a comma, preserving existing empty-string handling
                        if ($queryParams[$key] -eq '') {
                            $queryParams[$key] = $value
                        }
                        else {
                            $queryParams[$key] = "{0},{1}" -f $queryParams[$key], $value
                        }
                    }
                    else {
                        $queryParams[$key] = $value
                    }
                }
        }
    }

    [PSCustomObject]@{
        URL         = $url
        QueryParams = $queryParams
        QueryString = ($queryParams.Keys | ForEach-Object { "$_=$($queryParams[$_])" }) -Join "&"
    } | ConvertTo-Json -Depth 2 -EscapeHandling None
}

Export-ModuleMember -Function Convert-UrlToElixAutocompleteFormat
Export-ModuleMember -Function Save-ElxInternals