Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$repoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..')
$protoRoot = Join-Path $repoRoot 'src\ZB.MOM.WW.MxGateway.Contracts\Protos'
$outputRoot = Join-Path $PSScriptRoot 'internal\generated'
$modulePath = 'gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated'
$protoc = 'C:\Users\dohertj2\AppData\Local\Microsoft\WinGet\Packages\Google.Protobuf_Microsoft.Winget.Source_8wekyb3d8bbwe\bin\protoc.exe'
$goPluginPath = 'C:\Users\dohertj2\go\bin'

if (-not (Test-Path $protoc)) {
    throw "protoc was not found at $protoc. See docs/ToolchainLinks.md."
}

foreach ($pluginName in @('protoc-gen-go.exe', 'protoc-gen-go-grpc.exe')) {
    $pluginPath = Join-Path $goPluginPath $pluginName
    if (-not (Test-Path $pluginPath)) {
        throw "$pluginName was not found at $pluginPath. See docs/ToolchainLinks.md."
    }
}

New-Item -ItemType Directory -Path $outputRoot -Force | Out-Null
Get-ChildItem -Path $outputRoot -Filter '*.pb.go' -File | Remove-Item

$env:Path = "$goPluginPath;$env:Path"

& $protoc `
    --proto_path=$protoRoot `
    --go_out=$outputRoot `
    --go_opt=paths=source_relative `
    "--go_opt=Mmxaccess_gateway.proto=$modulePath;generated" `
    "--go_opt=Mmxaccess_worker.proto=$modulePath;generated" `
    "--go_opt=Mgalaxy_repository.proto=$modulePath;generated" `
    mxaccess_gateway.proto `
    mxaccess_worker.proto `
    galaxy_repository.proto

& $protoc `
    --proto_path=$protoRoot `
    --go-grpc_out=$outputRoot `
    --go-grpc_opt=paths=source_relative `
    "--go-grpc_opt=Mmxaccess_gateway.proto=$modulePath;generated" `
    "--go-grpc_opt=Mgalaxy_repository.proto=$modulePath;generated" `
    mxaccess_gateway.proto `
    galaxy_repository.proto

