#!/bin/bash

# Function to kill background processes on exit
cleanup() {
    echo "Stopping services..."
    kill $(jobs -p) 2>/dev/null
    exit
}

trap cleanup SIGINT SIGTERM

echo "🚀 Starting GoHorseJobs Development Environment..."

# Update Backend
echo "🔹 Checking Backend Dependencies..."
cd backend && go mod tidy
# Generate Swagger Docs
# Generate Swagger Docs
if ! command -v swag &> /dev/null; then
    if [ -f "$HOME/go/bin/swag" ]; then
        export PATH=$PATH:$HOME/go/bin
    else
        echo "⚠️ 'swag' command not found. Installing..."
        go install github.com/swaggo/swag/cmd/swag@latest
        export PATH=$PATH:$HOME/go/bin
    fi
fi

echo "🔹 Generating Swagger Docs..."
swag init -g cmd/api/main.go --parseDependency --parseInternal
cd ..

# Check Frontend Dependencies
echo "🔹 Checking Frontend Dependencies..."
if [ ! -d "frontend/node_modules" ]; then
    echo "⚠️ node_modules not found. Running npm install..."
    cd frontend && npm install && cd ..
fi

# Start Backend
echo "🔹 Starting Backend (Go) on port 8521..."
(cd backend && go run cmd/api/main.go) &
BACKEND_PID=$!

# Wait a moment for backend to initialize
sleep 2

# Start Frontend
echo "🔹 Starting Frontend (Next.js) on port 8963..."
(cd frontend && npm run dev -- -p 8963) &
FRONTEND_PID=$!

echo ""
echo "📡 Services running:"
echo "   - Backend:  http://localhost:8521"
echo "   - Frontend: http://localhost:8963"
echo ""

# Wait for both processes
wait $BACKEND_PID $FRONTEND_PID
