#!/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 with Seeding..."

# ----------------------------------------
# 1. Update Backend & Docs
# ----------------------------------------
echo "🔹 Checking Backend Dependencies..."
cd backend && go mod tidy
echo "🔹 Generating Swagger Docs..."
if command -v swag &> /dev/null; then
    swag init -g cmd/api/main.go --parseDependency --parseInternal
fi
cd ..

# ----------------------------------------
# 2. Reset Database (Clean Slate)
# ----------------------------------------
echo "🔹 Checking Seeder Dependencies..."
cd seeder-api
if [ ! -d "node_modules" ]; then
    npm install
fi

echo "🔹 Resetting Database (Dropping Tables)..."
# This needs DB to be up. DB is assumed up (Postgres service).
npm run seed:reset
if [ $? -ne 0 ]; then
    echo "❌ Database reset failed! Check DB connection."
    cleanup
fi
cd ..

# ----------------------------------------
# 3. Start Backend (Run Migrations)
# ----------------------------------------
echo "🔹 Starting Backend (Go)..."
(cd backend && go run cmd/api/main.go) &
BACKEND_PID=$!

echo "⏳ Waiting for Backend to be ready (and migrations to finish)..."
# Poll health endpoint
MAX_RETRIES=30
COUNT=0
URL="http://localhost:8080/health"

while ! curl -s $URL > /dev/null; do
    echo "   ... waiting for backend ($COUNT/$MAX_RETRIES)"
    sleep 1
    COUNT=$((COUNT+1))
    if [ $COUNT -ge $MAX_RETRIES ]; then
        echo "❌ Backend failed to start in time."
        cleanup
    fi
done

echo "✅ Backend is UP and Migrations Applied!"

# ----------------------------------------
# 4. Seed Data (Populate Tables)
# ----------------------------------------
echo "🔹 Seeding Database..."
cd seeder-api
npm run seed
if [ $? -ne 0 ]; then
    echo "❌ Seeding failed!"
    cleanup
fi
cd ..

# ----------------------------------------
# 4. Start Frontend
# ----------------------------------------
echo "🔹 Checking Frontend Dependencies..."
if [ ! -d "frontend/node_modules" ]; then
    cd frontend && npm install && cd ..
fi

echo "🔹 Starting Frontend (Next.js)..."
(cd frontend && npm run dev) &
FRONTEND_PID=$!

# Wait for both processes
wait $BACKEND_PID $FRONTEND_PID
