# Bootstrap MySQL+Redis in WSL (no Docker Desktop)
# Usage: npm run dev:infra:setup

$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "lib.ps1")
. (Join-Path $PSScriptRoot "ensure-infra.ps1")

$root = $script:DevConfig.ProjectRoot
$wslPath = Get-WslInfraScriptPath -Root $root
$fixMysqlPath = (Get-WslInfraScriptPath -Root $root) -replace 'wsl-infra\.sh$', 'fix-mysql-auth.sh'
$distro = Ensure-DevWslDistro

Write-DevLog "=== wsl infra bootstrap (distro: $distro) ===" "Info"

$checkCode = Invoke-DevWsl -BashCommand "command -v mysql"
if ($checkCode -ne 0) {
    Write-DevLog "first-time install mysql+redis in WSL (may prompt sudo password)..." "Warn"
    $code = Invoke-DevWsl -BashCommand "export MYSQL_HOST_PORT=3307 MYSQL_ROOT_PASSWORD=changeme; bash '$wslPath' install"
} else {
    $code = Invoke-DevWsl -BashCommand "export MYSQL_HOST_PORT=3307 MYSQL_ROOT_PASSWORD=changeme; bash '$wslPath' start"
}

if ($code -ne 0) {
    throw "wsl infra bootstrap failed (distro: $distro)"
}

Invoke-DevWsl -BashCommand "sudo bash '$fixMysqlPath'" | Out-Null

$ports = Test-NativeInfraPorts -Root $root
if (-not $ports.Ok) {
    throw "wsl infra ports not reachable from Windows (host=$($ports.Host))"
}

$envFile = Join-Path $root ".env"
if (Test-Path $envFile) {
    $hostName = $ports.Host
    $content = Get-Content $envFile -Raw -Encoding UTF8
    $content = $content -replace '(?m)^DATABASE_URL=.*$', "DATABASE_URL=mysql://root:changeme@${hostName}:3307/chajia"
    $content = $content -replace '(?m)^REDIS_URL=.*$', "REDIS_URL=redis://${hostName}:6379"
    [System.IO.File]::WriteAllText($envFile, $content.TrimEnd() + "`n", [System.Text.UTF8Encoding]::new($false))
    Write-DevLog "patched .env infra host -> $hostName" "Ok"
}

Apply-DevInfraEnv -Root $root
Write-DevLog "wsl mysql:3307 + redis:6379 ready (host=$($ports.Host))" "Ok"
Write-DevLog "DEV_INFRA_MODE=native in .env, then: npm run dev:start" "Ok"
