#!/bin/bash
# =============================================================================
# Presence Service - Individual Deployment Script
# =============================================================================
# Uses shared infrastructure from main docker-compose.yml
# =============================================================================

set -e

SERVICE_NAME="presence-service"
CONTAINER_NAME="rwa-presence-service"
IMAGE_NAME="services-presence-service"
PORT=3011
HEALTH_ENDPOINT="http://localhost:${PORT}/api/v1/health"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERVICES_DIR="$(dirname "$SCRIPT_DIR")"

# Load environment from parent services directory (shared .env)
load_env() {
    if [ -f "$SERVICES_DIR/.env" ]; then
        export $(cat "$SERVICES_DIR/.env" | grep -v '^#' | xargs)
        log_info "Loaded .env from $SERVICES_DIR"
    elif [ -f "$SCRIPT_DIR/.env.production" ]; then
        export $(cat "$SCRIPT_DIR/.env.production" | grep -v '^#' | xargs)
        log_info "Loaded .env.production from $SCRIPT_DIR"
    fi
}

case "$1" in
    build)
        log_info "Building $SERVICE_NAME..."
        docker build -t "$IMAGE_NAME" "$SCRIPT_DIR"
        log_success "$SERVICE_NAME built successfully"
        ;;

    build-no-cache)
        log_info "Building $SERVICE_NAME (no cache)..."
        docker build --no-cache -t "$IMAGE_NAME" "$SCRIPT_DIR"
        log_success "$SERVICE_NAME built successfully"
        ;;

    start)
        load_env
        log_info "Starting $SERVICE_NAME using shared infrastructure..."
        cd "$SERVICES_DIR"
        # Use --no-deps to avoid recreating infrastructure that's already running
        docker compose up -d --no-deps "$SERVICE_NAME"
        log_success "$SERVICE_NAME started"
        log_info "Waiting for service to be healthy..."
        sleep 5
        bash "$SCRIPT_DIR/deploy.sh" health
        ;;

    start-deps)
        log_info "Starting dependencies only (for local development)..."
        cd "$SCRIPT_DIR"
        docker compose -f docker-compose.dev.yml up -d
        log_success "Dependencies started"
        ;;

    stop)
        log_info "Stopping $SERVICE_NAME..."
        docker stop "$CONTAINER_NAME" 2>/dev/null || true
        docker rm "$CONTAINER_NAME" 2>/dev/null || true
        log_success "$SERVICE_NAME stopped"
        ;;

    stop-deps)
        log_info "Stopping dependencies..."
        cd "$SCRIPT_DIR"
        docker compose -f docker-compose.dev.yml down
        log_success "Dependencies stopped"
        ;;

    restart)
        bash "$SCRIPT_DIR/deploy.sh" stop
        bash "$SCRIPT_DIR/deploy.sh" start
        ;;

    up)
        load_env
        log_info "Starting $SERVICE_NAME in foreground..."
        cd "$SERVICES_DIR"
        # Use --no-deps to avoid recreating infrastructure that's already running
        docker compose up --no-deps "$SERVICE_NAME"
        ;;

    logs)
        docker logs -f "$CONTAINER_NAME"
        ;;

    logs-tail)
        docker logs --tail 100 "$CONTAINER_NAME"
        ;;

    logs-all)
        cd "$SERVICES_DIR"
        docker compose logs -f "$SERVICE_NAME"
        ;;

    status)
        if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
            log_success "$SERVICE_NAME is running"
            docker ps --filter "name=$CONTAINER_NAME" --format "table {{.Status}}\t{{.Ports}}"
        else
            log_warn "$SERVICE_NAME is not running"
        fi
        ;;

    health)
        log_info "Checking health of $SERVICE_NAME..."
        if curl -sf "$HEALTH_ENDPOINT" > /dev/null 2>&1; then
            HEALTH=$(curl -s "$HEALTH_ENDPOINT")
            log_success "$SERVICE_NAME is healthy"
            echo "$HEALTH" | jq . 2>/dev/null || echo "$HEALTH"
        else
            log_error "$SERVICE_NAME health check failed"
            exit 1
        fi
        ;;

    init-db)
        log_info "Creating database rwa_presence..."
        docker exec rwa-postgres psql -U rwa_user -d postgres -c "CREATE DATABASE rwa_presence;" 2>/dev/null || \
            log_warn "Database may already exist"
        log_success "Database rwa_presence created (or already exists)"
        log_info "Running Prisma db push to create tables..."
        docker exec "$CONTAINER_NAME" npx prisma db push --skip-generate 2>/dev/null || \
            log_warn "Could not push schema (container may not be running)"
        ;;

    migrate)
        log_info "Running migrations for $SERVICE_NAME..."
        docker exec "$CONTAINER_NAME" npx prisma migrate deploy
        log_success "Migrations completed"
        ;;

    migrate-dev)
        log_info "Running dev migrations for $SERVICE_NAME..."
        docker exec "$CONTAINER_NAME" npx prisma migrate dev
        ;;

    db-push)
        log_info "Pushing schema to database..."
        docker exec "$CONTAINER_NAME" npx prisma db push
        log_success "Schema pushed"
        ;;

    prisma-studio)
        log_info "Starting Prisma Studio..."
        docker exec -it "$CONTAINER_NAME" npx prisma studio
        ;;

    shell)
        log_info "Opening shell in $SERVICE_NAME container..."
        docker exec -it "$CONTAINER_NAME" sh
        ;;

    test)
        log_info "Running tests for $SERVICE_NAME..."
        cd "$SCRIPT_DIR"
        npm test
        ;;

    test-unit)
        log_info "Running unit tests..."
        cd "$SCRIPT_DIR"
        npm run test:unit
        ;;

    test-integration)
        log_info "Running integration tests..."
        cd "$SCRIPT_DIR"
        npm run test:integration
        ;;

    test-e2e)
        log_info "Running E2E tests..."
        cd "$SCRIPT_DIR"
        npm run test:e2e
        ;;

    clean)
        log_info "Cleaning up..."
        docker stop "$CONTAINER_NAME" 2>/dev/null || true
        docker rm "$CONTAINER_NAME" 2>/dev/null || true
        log_success "Cleanup completed"
        ;;

    clean-all)
        log_info "Cleaning $SERVICE_NAME (removing container and image)..."
        docker stop "$CONTAINER_NAME" 2>/dev/null || true
        docker rm "$CONTAINER_NAME" 2>/dev/null || true
        docker rmi "$IMAGE_NAME" 2>/dev/null || true
        log_success "$SERVICE_NAME fully cleaned"
        ;;

    *)
        echo "Usage: $0 {command}"
        echo ""
        echo "Build Commands:"
        echo "  build          - Build Docker image"
        echo "  build-no-cache - Build Docker image without cache"
        echo ""
        echo "Service Commands:"
        echo "  start          - Start using shared infrastructure"
        echo "  start-deps     - Start dependencies only (for local development)"
        echo "  stop           - Stop the service container"
        echo "  stop-deps      - Stop dependencies only"
        echo "  restart        - Restart the service"
        echo "  up             - Start in foreground mode"
        echo ""
        echo "Monitoring Commands:"
        echo "  logs           - Follow logs"
        echo "  logs-tail      - Show last 100 log lines"
        echo "  logs-all       - Follow logs via docker compose"
        echo "  status         - Show service status"
        echo "  health         - Check service health"
        echo ""
        echo "Database Commands:"
        echo "  init-db        - Create database and push schema"
        echo "  migrate        - Run database migrations (production)"
        echo "  migrate-dev    - Run dev migrations"
        echo "  db-push        - Push Prisma schema to database"
        echo "  prisma-studio  - Open Prisma Studio"
        echo ""
        echo "Development Commands:"
        echo "  shell          - Open shell in container"
        echo "  test           - Run all tests"
        echo "  test-unit      - Run unit tests only"
        echo "  test-integration - Run integration tests only"
        echo "  test-e2e       - Run E2E tests only"
        echo ""
        echo "Maintenance Commands:"
        echo "  clean          - Remove container"
        echo "  clean-all      - Remove container and image"
        exit 1
        ;;
esac
