[CmdletBinding()]
param(
    [string]$BaseUrl = '',
    [string]$Username = '',
    [string]$Password = '',
    [string]$RestrictedUsername = '',
    [string]$RestrictedPassword = '',
    [string]$RestrictedAllowedBranches = ''
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

$spotCheckPath = Join-Path $PSScriptRoot 'post_deploy_spot_check.ps1'
if (-not (Test-Path -LiteralPath $spotCheckPath)) {
    throw "Post-deploy spot check script not found: $spotCheckPath"
}

if ([string]::IsNullOrWhiteSpace($BaseUrl)) {
    $BaseUrl = if ([string]::IsNullOrWhiteSpace($env:CCW_BASE_URL)) { 'http://127.0.0.1/CCW' } else { $env:CCW_BASE_URL }
}

if ([string]::IsNullOrWhiteSpace($Username)) {
    $Username = if ([string]::IsNullOrWhiteSpace($env:CCW_SMOKE_USERNAME)) { 'admin' } else { $env:CCW_SMOKE_USERNAME }
}

if ([string]::IsNullOrWhiteSpace($Password)) {
    $Password = if ([string]::IsNullOrWhiteSpace($env:CCW_SMOKE_PASSWORD)) { 'admin123' } else { $env:CCW_SMOKE_PASSWORD }
}

if ([string]::IsNullOrWhiteSpace($RestrictedUsername)) {
    $RestrictedUsername = [string]$env:CCW_RESTRICTED_SMOKE_USERNAME
}

if ([string]::IsNullOrWhiteSpace($RestrictedPassword)) {
    $RestrictedPassword = [string]$env:CCW_RESTRICTED_SMOKE_PASSWORD
}

if ([string]::IsNullOrWhiteSpace($RestrictedAllowedBranches)) {
    $RestrictedAllowedBranches = [string]$env:CCW_RESTRICTED_ALLOWED_BRANCHES
}

$invokeParams = @{
    BaseUrl = $BaseUrl
    Username = $Username
    Password = $Password
}

$allowedBranchList = @()
if (-not [string]::IsNullOrWhiteSpace($RestrictedAllowedBranches)) {
    $allowedBranchList = @(
        $RestrictedAllowedBranches -split '[,;]' |
            Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
            ForEach-Object { $_.Trim() } |
            Select-Object -Unique
    )
}

if (-not [string]::IsNullOrWhiteSpace($RestrictedUsername) -and -not [string]::IsNullOrWhiteSpace($RestrictedPassword)) {
    $invokeParams['RestrictedUsername'] = $RestrictedUsername
    $invokeParams['RestrictedPassword'] = $RestrictedPassword
    if ($allowedBranchList.Count -gt 0) {
        $invokeParams['RestrictedAllowedBranches'] = $allowedBranchList
    }
}

$artifactDir = [string]$env:CCW_CI_ARTIFACT_DIR
$transcriptStarted = $false
$transcriptPath = ''
$summaryPath = ''
$restrictedUsernameSummary = if ([string]::IsNullOrWhiteSpace($RestrictedUsername)) { '[none]' } else { $RestrictedUsername }
$restrictedBranchesSummary = if ($allowedBranchList.Count -eq 0) { '[none]' } else { ($allowedBranchList -join ', ') }

try {
    if (-not [string]::IsNullOrWhiteSpace($artifactDir)) {
        New-Item -ItemType Directory -Path $artifactDir -Force | Out-Null
        $transcriptPath = Join-Path $artifactDir 'ci-post-deploy-spot-check.log'
        $summaryPath = Join-Path $artifactDir 'ci-post-deploy-spot-check-summary.txt'
        Start-Transcript -Path $transcriptPath -Force | Out-Null
        $transcriptStarted = $true
    }

    Write-Output ("[ci-post-deploy] BaseUrl={0}" -f $BaseUrl)
    Write-Output ("[ci-post-deploy] Username={0}" -f $Username)
    Write-Output ("[ci-post-deploy] RestrictedUsername={0}" -f $restrictedUsernameSummary)
    Write-Output ("[ci-post-deploy] RestrictedAllowedBranches={0}" -f $restrictedBranchesSummary)

    & $spotCheckPath @invokeParams

    if ($summaryPath -ne '') {
        @(
            'result=passed'
            ('base_url={0}' -f $BaseUrl)
            ('username={0}' -f $Username)
            ('restricted_username={0}' -f $restrictedUsernameSummary)
            ('restricted_allowed_branches={0}' -f $restrictedBranchesSummary)
        ) | Set-Content -Path $summaryPath -Encoding utf8
    }
} catch {
    if ($summaryPath -ne '') {
        @(
            'result=failed'
            ('base_url={0}' -f $BaseUrl)
            ('username={0}' -f $Username)
            ('restricted_username={0}' -f $restrictedUsernameSummary)
            ('restricted_allowed_branches={0}' -f $restrictedBranchesSummary)
            ('message={0}' -f $_.Exception.Message)
        ) | Set-Content -Path $summaryPath -Encoding utf8
    }
    throw
} finally {
    if ($transcriptStarted) {
        Stop-Transcript | Out-Null
    }
}
