# 生成 Swagger 文档
# 用法: .\scripts\gen-swagger.ps1

$swag = "$env:USERPROFILE\go\bin\swag.exe"
$project = "E:\workspaces\sc-lktx-mp\sc-lktx-backend"
$output = "$project\docs"

Write-Host "=== 1. 生成 Swagger 文档 ==="
& $swag init -g cmd/server/main.go --output $output --parseDependency --parseDepth 1

if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 1) {
    Write-Host "swag init failed with code $LASTEXITCODE" -ForegroundColor Red
    exit $LASTEXITCODE
}

Write-Host "=== 2. 转换鉴权格式 (apiKey -> Bearer, 全局继承) ==="
$json = Get-Content "$output\swagger.json" -Raw | ConvertFrom-Json

$bearerScheme = @{
    type = "http"
    scheme = "bearer"
    bearerFormat = "JWT"
}

$json.PSObject.Properties.Remove('securityDefinitions')

$components = $json.components
if (-not $components) {
    $components = New-Object PSObject
    $json | Add-Member -Name 'components' -Value $components -MemberType NoteProperty -Force
}
$components | Add-Member -Name 'securitySchemes' -Value @{ BearerAuth = $bearerScheme } -MemberType NoteProperty -Force

# 移除所有接口上的 security（避免覆盖全局继承）
function Remove-SecurityFromPaths($obj) {
    if ($obj.PSObject.Properties.Name -contains 'security') {
        $obj.PSObject.Properties.Remove('security')
    }
    foreach ($prop in $obj.PSObject.Properties) {
        if ($prop.Value -is [PSCustomObject]) {
            Remove-SecurityFromPaths $prop.Value
        } elseif ($prop.Value -is [System.Collections.ICollection]) {
            foreach ($item in $prop.Value) {
                if ($item -is [PSCustomObject]) {
                    Remove-SecurityFromPaths $item
                }
            }
        }
    }
}
Remove-SecurityFromPaths $json.paths

# 添加全局 security（所有接口继承此鉴权）
$json | Add-Member -Name 'security' -Value @(@{ BearerAuth = @() }) -MemberType NoteProperty -Force

$json | ConvertTo-Json -Depth 32 | Set-Content "$output\swagger.json"

# 同步修改 docs.go
$docsPath = "$output\docs.go"
$content = Get-Content $docsPath -Raw

# 替换 securityDefinitions 为 components/securitySchemes (bearer 格式)
$oldSecurity = '"securityDefinitions": {
        "BearerAuth": {
            "type": "apiKey",
            "name": "Authorization",
            "in": "header"
        }
    },'
$newSecurity = '"components": {
        "securitySchemes": {
            "BearerAuth": {
                "bearerFormat": "JWT",
                "type": "http",
                "scheme": "bearer"
            }
        }
    },
    "security": [
        {
            "BearerAuth": []
        }
    ],'
$content = $content.Replace($oldSecurity, $newSecurity)

# 移除所有接口上的 security（避免覆盖全局继承）
$content = $content -replace '\s{12,}"security": \[\s*\{\s*"BearerAuth":\s*\[\]\s*\}\s*\],?\s*', "`r`n"
Write-Host "   已移除接口级 security"

Set-Content $docsPath $content
Write-Host "   docs.go 同步更新（全局继承）"

# 清理临时文件，只保留 docs.go
Remove-Item "$output\swagger.json", "$output\swagger.yaml" -Force -ErrorAction SilentlyContinue
Write-Host "   已清理 swagger.json / swagger.yaml"

Write-Host "=== 3. 验证编译 ==="
Set-Location $project
go build ./...
Write-Host "=== 完成 ===" -ForegroundColor Green
