[CmdletBinding()]
param(
    [string]$OutputDirectory = (Join-Path $PSScriptRoot '..\artifacts\publish')
)

$ErrorActionPreference = 'Stop'
$repositoryRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path
$publishRoot = [IO.Path]::GetFullPath(
    $(if ([IO.Path]::IsPathRooted($OutputDirectory)) {
        $OutputDirectory
    }
    else {
        Join-Path $repositoryRoot $OutputDirectory
    }))
$clientRoot = Join-Path $repositoryRoot 'src\Eis.Web\ClientApp'

Push-Location $clientRoot
try {
    $npmInstallArgs = @('ci')
    & npm @npmInstallArgs
    $npmInstallExitCode = $LASTEXITCODE
    if ($npmInstallExitCode -ne 0) {
        throw "npm ci 失败，退出码：$npmInstallExitCode"
    }

    $npmBuildArgs = @('run', 'build')
    & npm @npmBuildArgs
    $npmBuildExitCode = $LASTEXITCODE
    if ($npmBuildExitCode -ne 0) {
        throw "Vue 生产构建失败，退出码：$npmBuildExitCode"
    }
}
finally {
    Pop-Location
}

$projects = @(
    @{
        Project = Join-Path $repositoryRoot 'src\Eis.Web\Eis.Web.csproj'
        Output = Join-Path $publishRoot 'web'
    },
    @{
        Project = Join-Path $repositoryRoot 'src\Eis.Tools\Eis.Tools.csproj'
        Output = Join-Path $publishRoot 'tools'
    }
)

foreach ($item in $projects) {
    $nativeArgs = @(
        'publish'
        $item.Project
        '--configuration'
        'Release'
        '--output'
        $item.Output
    )
    & dotnet @nativeArgs
    $exitCode = $LASTEXITCODE
    if ($exitCode -ne 0) {
        throw "dotnet publish 失败，退出码：$exitCode"
    }
}

Write-Host "Web 发布目录：$(Join-Path $publishRoot 'web')"
Write-Host "数据库工具目录：$(Join-Path $publishRoot 'tools')"
Write-Host "工具示例：dotnet $(Join-Path $publishRoot 'tools\Eis.Tools.dll') database seed --dry-run"
