@echo off
setlocal

set "SCRIPT_DIR=%~dp0"
cd /d "%SCRIPT_DIR%"
if errorlevel 1 goto fail_cd

set "APP_NAME=sproutgate-backend"
set "DIST_DIR=%SCRIPT_DIR%dist"
set "OUTPUT_FILE=%DIST_DIR%\%APP_NAME%"
set "GOCACHE_DIR=%TEMP%\%APP_NAME%-gocache"

where go >nul 2>nul
if errorlevel 1 goto fail_go

if not exist "%DIST_DIR%" mkdir "%DIST_DIR%"
if errorlevel 1 goto fail_dist

if not exist "%GOCACHE_DIR%" mkdir "%GOCACHE_DIR%"

echo [INFO] Working directory: %CD%
echo [INFO] Building %APP_NAME% for linux amd64...
echo [INFO] Output: %OUTPUT_FILE%

set "CGO_ENABLED=0"
set "GOOS=linux"
set "GOARCH=amd64"
set "GOCACHE=%GOCACHE_DIR%"

echo [INFO] Regenerating Swagger docs (swag)...
go run github.com/swaggo/swag/cmd/swag@latest init -g main.go -o docs --parseInternal
if errorlevel 1 goto fail_build

go build -trimpath -ldflags "-s -w" -o "%OUTPUT_FILE%" .
if errorlevel 1 goto fail_build

echo [OK] Build completed: %OUTPUT_FILE%
exit /b 0

:fail_cd
echo [ERROR] Cannot change to script directory: %SCRIPT_DIR%
goto pause_and_exit

:fail_go
echo [ERROR] Go was not found in PATH.
goto pause_and_exit

:fail_dist
echo [ERROR] Cannot create output directory: %DIST_DIR%
goto pause_and_exit

:fail_build
echo [ERROR] Build failed. Check the Go output above.
goto pause_and_exit

:pause_and_exit
pause
exit /b 1
