#!/bin/bash

# Start Queue Worker - Development Helper Script
# This script starts the Laravel queue worker for email processing
# Automatically runs in a detached screen session named 'showprima-queue'
#
# Usage:
#   ./scripts/start-queue-worker.sh          # Start in screen (background)
#   ./scripts/start-queue-worker.sh --fg     # Start in foreground (no screen)

set -e

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

# Parse arguments
RUN_IN_FOREGROUND=false
for arg in "$@"; do
    case $arg in
        --fg|--foreground)
            RUN_IN_FOREGROUND=true
            shift
            ;;
    esac
done

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Show Prima Queue Worker${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# Change to project root
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$PROJECT_ROOT"

# Dynamically set screen name based on the project directory
ENV_NAME=$(basename "$PROJECT_ROOT")
SCREEN_NAME="showprima-queue-$ENV_NAME"

# Check if already running (either in screen or as process)
if screen -list | grep -q "$SCREEN_NAME"; then
    echo -e "${YELLOW}⚠️  Queue worker is already running in screen session '$SCREEN_NAME'!${NC}"
    echo ""
    echo "Options:"
    echo "  1. View the worker: ${BLUE}screen -r $SCREEN_NAME${NC}"
    echo "  2. Stop the worker: ${BLUE}screen -S $SCREEN_NAME -X quit${NC}"
    echo "  3. Restart the worker: Stop it first, then run this script again"
    echo ""
    exit 1
elif pgrep -f "queue:work" > /dev/null; then
    echo -e "${YELLOW}⚠️  Queue worker is already running (not in screen)!${NC}"
    echo ""
    echo "Running processes:"
    ps aux | grep "queue:work" | grep -v grep
    echo ""
    read -p "Kill existing worker and restart? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Stopping existing workers...${NC}"
        pkill -f "$PROJECT_ROOT.*queue:work" || true
        sleep 2
    else
        echo -e "${RED}Exiting. Stop the existing worker first.${NC}"
        exit 1
    fi
fi

# Check pending jobs (skip db_count if function doesn't exist)
if command -v db_count &> /dev/null; then
    PENDING_JOBS=$(db_count "jobs" 2>/dev/null || echo "0")
else
    PENDING_JOBS=$(php artisan tinker --execute="echo DB::table('jobs')->count();" 2>/dev/null | grep -o '[0-9]*' | tail -1 || echo "0")
fi
FAILED_JOBS=$(php artisan queue:failed --json 2>/dev/null | grep -c "\"id\"" || echo "0")

echo -e "${GREEN}📊 Queue Status:${NC}"
echo "   Pending jobs: $PENDING_JOBS"
echo "   Failed jobs: $FAILED_JOBS"
echo ""

if [ "$FAILED_JOBS" -gt 0 ]; then
    echo -e "${YELLOW}Found $FAILED_JOBS failed jobs.${NC}"
    if [ "$RUN_IN_FOREGROUND" = false ]; then
        echo "   Run 'php artisan queue:retry all' to retry failed jobs"
    else
        read -p "Retry all failed jobs? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            echo -e "${GREEN}Retrying failed jobs...${NC}"
            php artisan queue:retry all
            echo ""
        fi
    fi
fi

echo -e "${GREEN}🚀 Starting queue worker...${NC}"
echo ""
echo -e "${YELLOW}Worker Configuration:${NC}"
echo "   Queue: database (critical, default, tickets, bulk)"
echo "   Priority: critical > default > tickets > bulk"
echo "   Tries: 3 attempts"
echo "   Timeout: 600 seconds (10 minutes)"
echo "   Sleep: 3 seconds between jobs"
echo "   Max Time: 3600 seconds (1 hour)"
echo "   Max Jobs: 500 jobs per worker"
echo ""

# Queue worker command with priority ordering
# critical: Password resets, 2FA, urgent emails
# default: Transactional emails (order confirmations, tickets)
# tickets: Ticket-specific operations
# bulk: Non-urgent bulk invitations, account setup campaigns
WORKER_CMD="php artisan queue:work database --queue=critical,default,tickets,bulk --tries=3 --timeout=600 --sleep=3 --max-time=3600 --max-jobs=500 --verbose"

if [ "$RUN_IN_FOREGROUND" = true ]; then
    # Run in foreground (original behavior)
    echo -e "${YELLOW}📝 Monitoring:${NC}"
    echo "   Logs: storage/logs/laravel-$(date +%Y-%m-%d).log"
    echo "   Mailpit: http://localhost:8025"
    echo ""
    echo -e "${GREEN}Press Ctrl+C to stop the worker${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""

    eval $WORKER_CMD
else
    # Run in detached screen session
    echo -e "${BLUE}Starting in screen session '$SCREEN_NAME'${NC}"
    echo ""
    echo -e "${YELLOW}📝 Management:${NC}"
    echo "   View worker: ${BLUE}screen -r $SCREEN_NAME${NC}"
    echo "   Detach: Press ${BLUE}Ctrl+A, then D${NC}"
    echo "   Stop worker: ${BLUE}screen -S $SCREEN_NAME -X quit${NC}"
    echo "   Logs: storage/logs/laravel-$(date +%Y-%m-%d).log"
    echo ""

    # Create screen session with queue worker
    screen -dmS "$SCREEN_NAME" bash -c "cd $PROJECT_ROOT && $WORKER_CMD"

    # Wait a moment and verify it started
    sleep 1

    if screen -list | grep -q "$SCREEN_NAME"; then
        echo -e "${GREEN}✅ Queue worker started successfully!${NC}"
        echo ""
        echo "The worker is now running in the background."
        echo "Use ${BLUE}screen -r $SCREEN_NAME${NC} to view it."
    else
        echo -e "${RED}❌ Failed to start queue worker in screen${NC}"
        echo ""
        echo "Try running with --fg flag to see errors:"
        echo "  ${BLUE}./scripts/start-queue-worker.sh --fg${NC}"
        exit 1
    fi
fi

echo -e "${GREEN}========================================${NC}"
