[CmdletBinding()]
param(
  [string]$ComposeFile = 'docker-compose.yml',
  [string]$ProjectName = 'goodwalk',
  [switch]$RunMigration,
  [string]$LegacyComposeFile,
  [string]$LegacyProjectName = 'legacy-goodwalk',
  [string]$LegacyWordPressContainer,
  [string]$LegacyDatabaseContainer,
  [string]$LegacyUploadsPath = '/var/www/html/wp-content/uploads',
  [string]$MySqlDatabase,
  [string]$MySqlUser,
  [string]$MySqlPassword,
  [switch]$SkipLegacyShutdown,
  [switch]$SkipBuild,
  [int]$HealthTimeoutSeconds = 120,
  [string]$HealthUrl = 'http://localhost/api/health'
)

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
. (Join-Path $scriptDir 'common.ps1')

$repoRoot = Split-Path -Parent $scriptDir
$composeFilePath = Resolve-AbsolutePath -BasePath $repoRoot -Path $ComposeFile

Write-Step 'Validating deployment prerequisites'
Assert-Command docker
Invoke-DockerCompose -ComposeFile $composeFilePath -ProjectName $ProjectName -WorkingDirectory $repoRoot -Arguments @('config')

if ($RunMigration) {
  Write-Step 'Running the WordPress migration step'
  $migrationScript = Join-Path $scriptDir 'migrate-wordpress.ps1'
  $migrationArgs = @(
    '-LegacyWordPressContainer', $LegacyWordPressContainer,
    '-LegacyUploadsPath', $LegacyUploadsPath
  )

  if ($LegacyDatabaseContainer) {
    $migrationArgs += @('-LegacyDatabaseContainer', $LegacyDatabaseContainer)
  } else {
    $migrationArgs += '-SkipDatabaseDump'
  }

  if ($MySqlDatabase) { $migrationArgs += @('-MySqlDatabase', $MySqlDatabase) }
  if ($MySqlUser) { $migrationArgs += @('-MySqlUser', $MySqlUser) }
  if ($MySqlPassword) { $migrationArgs += @('-MySqlPassword', $MySqlPassword) }

  & $migrationScript @migrationArgs

  if ($LASTEXITCODE -ne 0) {
    throw 'The WordPress migration step failed.'
  }
}

if ($LegacyComposeFile -and -not $SkipLegacyShutdown) {
  $legacyComposeFilePath = Resolve-AbsolutePath -BasePath $repoRoot -Path $LegacyComposeFile
  Write-Step 'Stopping the legacy WordPress stack'
  Invoke-DockerCompose -ComposeFile $legacyComposeFilePath -ProjectName $LegacyProjectName -WorkingDirectory $repoRoot -Arguments @('down')
}

Write-Step 'Building and starting the new stack'
$upArgs = @('up', '-d', '--remove-orphans')
if (-not $SkipBuild) {
  $upArgs += '--build'
}

Invoke-DockerCompose -ComposeFile $composeFilePath -ProjectName $ProjectName -WorkingDirectory $repoRoot -Arguments $upArgs

Write-Step 'Waiting for the new site to become healthy'
Wait-ForHttpOk -Url $HealthUrl -TimeoutSeconds $HealthTimeoutSeconds

Write-Step 'Current container status'
Invoke-DockerCompose -ComposeFile $composeFilePath -ProjectName $ProjectName -WorkingDirectory $repoRoot -Arguments @('ps')

Write-Step 'Deployment completed'
Write-Host "Health check passed at $HealthUrl"
