#!/bin/bash

# Start Development Servers - All-in-one Dev Environment Startup
# Starts Laravel API, Queue Worker, and verifies Mailpit is running

set -e

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

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Show Prima Dev Environment${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Change to project root
cd "$(dirname "$0")/.."

# Load database helper functions
source "$(dirname "$0")/_db-helper.sh"

# Check prerequisites
echo -e "${YELLOW}Checking prerequisites...${NC}"

# Check PHP
if ! command -v php &> /dev/null; then
    echo -e "${RED}✗ PHP not found${NC}"
    exit 1
fi
echo -e "${GREEN}✓${NC} PHP $(php -r 'echo PHP_VERSION;')"

# Check MySQL
if ! db_test_connection; then
    echo -e "${RED}✗ MySQL connection failed${NC}"
    exit 1
fi
echo -e "${GREEN}✓${NC} MySQL connection"

# Check Mailpit
if ! lsof -i :8025 > /dev/null 2>&1; then
    echo -e "${YELLOW}⚠ Mailpit not running${NC}"
    read -p "Start Mailpit? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Starting Mailpit in background...${NC}"
        nohup mailpit > /dev/null 2>&1 &
        sleep 2
        if lsof -i :8025 > /dev/null 2>&1; then
            echo -e "${GREEN}✓${NC} Mailpit started"
        else
            echo -e "${RED}✗ Failed to start Mailpit${NC}"
            exit 1
        fi
    else
        echo -e "${YELLOW}⚠ Continuing without Mailpit${NC}"
    fi
else
    echo -e "${GREEN}✓${NC} Mailpit running"
fi

echo ""
echo -e "${YELLOW}Starting services...${NC}"
echo ""

# Function to cleanup on exit
cleanup() {
    echo ""
    echo -e "${YELLOW}Shutting down services...${NC}"

    # Kill background processes
    jobs -p | xargs -r kill 2>/dev/null || true

    # Kill queue worker if it exists
    pkill -f "queue:work" 2>/dev/null || true

    echo -e "${GREEN}Services stopped${NC}"
    exit 0
}

# Trap Ctrl+C
trap cleanup SIGINT SIGTERM

# Start Laravel API server
echo -e "${BLUE}[1/2]${NC} Starting Laravel API server on http://localhost:8000..."
php artisan serve --host=localhost --port=8000 > storage/logs/laravel-server.log 2>&1 &
LARAVEL_PID=$!
sleep 2

if lsof -i :8000 > /dev/null 2>&1; then
    echo -e "${GREEN}  ✓ Laravel API running (PID: $LARAVEL_PID)${NC}"
else
    echo -e "${RED}  ✗ Failed to start Laravel API${NC}"
    cat storage/logs/laravel-server.log
    exit 1
fi

# Start Queue Worker
echo -e "${BLUE}[2/2]${NC} Starting Queue Worker..."
php artisan queue:work database \
    --queue=critical,tickets,default \
    --tries=3 \
    --timeout=600 \
    --sleep=3 \
    --verbose > storage/logs/queue-worker.log 2>&1 &
QUEUE_PID=$!
sleep 2

if pgrep -f "queue:work" > /dev/null; then
    echo -e "${GREEN}  ✓ Queue Worker running (PID: $QUEUE_PID)${NC}"
else
    echo -e "${RED}  ✗ Failed to start Queue Worker${NC}"
    cat storage/logs/queue-worker.log
    exit 1
fi

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Development Environment Ready!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${YELLOW}Services Running:${NC}"
echo -e "  ${BLUE}Laravel API:${NC}      http://localhost:8000"
echo -e "  ${BLUE}Mailpit UI:${NC}       http://localhost:8025"
echo -e "  ${BLUE}Queue Worker:${NC}     Running (PID: $QUEUE_PID)"
echo ""
echo -e "${YELLOW}Logs:${NC}"
echo -e "  ${BLUE}Laravel:${NC}          tail -f storage/logs/laravel-server.log"
echo -e "  ${BLUE}Queue Worker:${NC}     tail -f storage/logs/queue-worker.log"
echo -e "  ${BLUE}Application:${NC}      tail -f storage/logs/laravel-$(date +%Y-%m-%d).log"
echo ""
echo -e "${YELLOW}Monitoring:${NC}"
echo -e "  ${BLUE}Queue Stats:${NC}      ./scripts/queue-monitor.sh"
echo -e "  ${BLUE}Test Emails:${NC}      ./scripts/test-email-system.sh"
echo ""
echo -e "${GREEN}Press Ctrl+C to stop all services${NC}"
echo ""

# Wait for user to press Ctrl+C
while true; do
    sleep 1
done
