#!/bin/bash
# =============================================================================
# Presence Service - Start All Services Script
# =============================================================================
# One-command startup for all required services (development mode).
# =============================================================================

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo -e "${YELLOW}🚀 Starting Presence Service and dependencies...${NC}"
echo ""

# Change to project directory
cd "$PROJECT_DIR"

# 1. Start infrastructure via Docker Compose
echo -e "${YELLOW}=== Starting Infrastructure ===${NC}"
if command -v docker &> /dev/null; then
    echo "Starting Docker containers..."
    docker compose -f docker-compose.dev.yml up -d

    # Wait for containers to be healthy
    echo "Waiting for services to be ready..."
    sleep 5

    # Check PostgreSQL
    echo -n "Waiting for PostgreSQL..."
    for i in {1..30}; do
        if docker exec presence-postgres-dev pg_isready -U postgres > /dev/null 2>&1; then
            echo -e " ${GREEN}✓ Ready${NC}"
            break
        fi
        echo -n "."
        sleep 1
    done

    # Check Redis
    echo -n "Waiting for Redis..."
    for i in {1..30}; do
        if docker exec presence-redis-dev redis-cli ping > /dev/null 2>&1; then
            echo -e " ${GREEN}✓ Ready${NC}"
            break
        fi
        echo -n "."
        sleep 1
    done

    # Check Kafka (takes longer)
    echo -n "Waiting for Kafka..."
    for i in {1..60}; do
        if nc -zv localhost 9092 > /dev/null 2>&1; then
            echo -e " ${GREEN}✓ Ready${NC}"
            break
        fi
        echo -n "."
        sleep 1
    done
else
    echo -e "${RED}✗ Docker not found. Please install Docker first.${NC}"
    exit 1
fi

echo ""

# 2. Initialize database
echo -e "${YELLOW}=== Initializing Database ===${NC}"
if [ -f "prisma/schema.prisma" ]; then
    echo "Running Prisma db push..."
    npx prisma db push --skip-generate 2>/dev/null || true
    echo -e "${GREEN}✓ Database initialized${NC}"
else
    echo -e "${YELLOW}⚠ No Prisma schema found, skipping database init${NC}"
fi

echo ""

# 3. Start Presence Service
echo -e "${YELLOW}=== Starting Presence Service ===${NC}"
echo "Starting NestJS in development mode..."
npm run start:dev &
SERVICE_PID=$!

# Wait for service to start
echo "Waiting for service to be ready (up to 30 seconds)..."
for i in {1..30}; do
    if curl -sf http://localhost:3011/api/v1/health > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Presence Service is running!${NC}"
        break
    fi
    if [ $i -eq 30 ]; then
        echo -e "${YELLOW}⚠ Service may still be starting...${NC}"
    fi
    sleep 1
    echo -n "."
done

echo ""
echo -e "${YELLOW}======================================${NC}"
echo -e "${GREEN}✓ All services started!${NC}"
echo -e "${YELLOW}======================================${NC}"
echo ""
echo -e "${BLUE}Service endpoints:${NC}"
echo "  • Presence Service: http://localhost:3011"
echo "  • Health Check:     http://localhost:3011/api/v1/health"
echo "  • API Docs:         http://localhost:3011/api/docs"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo "  • Run health check:  ./scripts/health-check.sh"
echo "  • Run tests:         npm test"
echo "  • View logs:         (in current terminal)"
echo ""
echo -e "${BLUE}To stop:${NC}"
echo "  • Stop service:      ./scripts/stop-service.sh"
echo "  • Stop all:          docker compose -f docker-compose.dev.yml down"
echo ""
