#!/usr/bin/env bash
set -euo pipefail

echo "[CI] Verifying Gorilla dependencies and WebSocket endpoint (WS) in Go-enabled environment"

cd app

echo ">> Checking Go toolchain..." 
if ! command -v go >/dev/null 2>&1; then
  echo "Go is not installed in this environment. Exiting.";
  exit 0
fi

echo ">> Fetching dependencies..."
go get -u github.com/gorilla/mux
go get -u github.com/gorilla/websocket

echo ">> Tidying modules..."
go mod tidy

echo ">> Building project..."
go build ./...

echo ">> Running server in background..."
go run main.go &
PID=$!
echo "[CI] Server PID: $PID"
sleep 2

echo ">> Testing WebSocket endpoint (ws://localhost:8080/ws/stats) using simple client..."
if command -v websocat >/dev/null 2>&1; then
  websocat -b ws://localhost:8080/ws/stats >/tmp/ws_test.txt &
  WS_PID=$!
  sleep 6
  kill $WS_PID 2>/dev/null || true
  echo "Captured output:"; head -n 5 /tmp/ws_test.txt || true
else
  echo "websocat not installed. Install to run WS test or use another client."
fi

echo ">> Cleaning up server process..."
kill $PID 2>/dev/null || true
wait $PID 2>/dev/null || true

echo "[CI] Verification script completed."
