@echo off
setlocal

cd /d "%~dp0"

where docker >nul 2>nul
if errorlevel 1 (
  echo [ERROR] Docker was not found. Install Docker Desktop first.
  pause
  exit /b 1
)

docker info >nul 2>nul
if errorlevel 1 (
  echo [NOTICE] Docker is not running. Start Docker Desktop manually, then run this script again.
  pause
  exit /b 1
)

docker compose version >nul 2>nul
if errorlevel 1 (
  echo [ERROR] The docker compose command is unavailable. Check your Docker Desktop installation.
  pause
  exit /b 1
)

where go >nul 2>nul
if errorlevel 1 (
  echo [ERROR] Go was not found. Install Go and add it to PATH first.
  pause
  exit /b 1
)

if not exist "API\.env" (
  echo [ERROR] API\.env is missing. The API cannot start.
  pause
  exit /b 1
)

echo [1/3] Releasing port 8123...
for /f "tokens=5" %%P in ('netstat -ano ^| findstr /R /C:":8123 .*LISTENING"') do (
  taskkill /F /PID %%P >nul 2>nul
)

echo [2/3] Checking and starting PostgreSQL and Redis containers...
docker compose -f "docker-compose.yml" up -d --wait --wait-timeout 60
if errorlevel 1 (
  echo [ERROR] PostgreSQL or Redis failed to start. Check the Docker output above.
  pause
  exit /b 1
)

echo [3/3] Starting the API. Press Ctrl+C to stop it.
pushd "API"
go run ./cmd/api
set "API_EXIT_CODE=%ERRORLEVEL%"
popd

if not "%API_EXIT_CODE%"=="0" (
  echo [ERROR] The API exited with code %API_EXIT_CODE%.
  pause
)

exit /b %API_EXIT_CODE%
