#!/bin/bash

# ========================================
# Queue Worker Manager Script
# ========================================
# Usage:
#   ./scripts/queue-manager.sh status   - Check queue worker status
#   ./scripts/queue-manager.sh start    - Start queue worker
#   ./scripts/queue-manager.sh stop     - Stop queue worker
#   ./scripts/queue-manager.sh restart  - Restart queue worker
#   ./scripts/queue-manager.sh check    - Check and start if not running
#   ./scripts/queue-manager.sh logs     - Show queue worker logs
# ========================================

# Get the script directory and project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
LOG_FILE="/tmp/queue-worker.log"

# Change to project directory
cd "$PROJECT_ROOT" || exit 1

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

# Function to check if queue worker is running
is_running() {
    pgrep -f "artisan queue:work" > /dev/null 2>&1
    return $?
}

# Function to get PID
get_pid() {
    pgrep -f "artisan queue:work"
}

# Function to check pending jobs
check_pending_jobs() {
    php artisan tinker --execute="echo \App\Jobs\GenerateSuratMasukFromDisposisi::class . ': ' . \DB::table('jobs')->count() . ' jobs pending';" 2>/dev/null || echo "Unable to check pending jobs"
}

# Function to start queue worker
start_worker() {
    if is_running; then
        echo -e "${YELLOW}Queue worker is already running (PID: $(get_pid))${NC}"
        return 0
    fi

    echo -e "${GREEN}Starting queue worker...${NC}"
    nohup php artisan queue:work --tries=3 --timeout=90 --sleep=3 --max-jobs=1000 --max-time=3600 >> "$LOG_FILE" 2>&1 &

    sleep 2

    if is_running; then
        echo -e "${GREEN}Queue worker started successfully (PID: $(get_pid))${NC}"
    else
        echo -e "${RED}Failed to start queue worker${NC}"
        echo "Check logs: $LOG_FILE"
        return 1
    fi
}

# Function to stop queue worker
stop_worker() {
    if ! is_running; then
        echo -e "${YELLOW}Queue worker is not running${NC}"
        return 0
    fi

    echo -e "${YELLOW}Stopping queue worker...${NC}"
    pkill -f "artisan queue:work"

    sleep 2

    if ! is_running; then
        echo -e "${GREEN}Queue worker stopped${NC}"
    else
        echo -e "${RED}Failed to stop queue worker, force killing...${NC}"
        pkill -9 -f "artisan queue:work"
    fi
}

# Function to show status
show_status() {
    echo "=========================================="
    echo "Queue Worker Status"
    echo "=========================================="

    if is_running; then
        echo -e "Status: ${GREEN}RUNNING${NC}"
        echo "PID: $(get_pid)"
    else
        echo -e "Status: ${RED}STOPPED${NC}"
    fi

    echo ""
    echo "Pending Jobs:"
    check_pending_jobs

    echo ""
    echo "Failed Jobs:"
    php artisan queue:failed --limit=5 2>/dev/null || echo "No failed jobs table or no failed jobs"

    echo "=========================================="
}

# Function to show logs
show_logs() {
    if [ -f "$LOG_FILE" ]; then
        echo "Last 50 lines of queue worker log:"
        echo "=========================================="
        tail -50 "$LOG_FILE"
    else
        echo "No log file found at $LOG_FILE"
    fi
}

# Function to check and start if not running
check_and_start() {
    echo "Checking queue worker status..."

    if is_running; then
        echo -e "${GREEN}Queue worker is running (PID: $(get_pid))${NC}"
    else
        echo -e "${YELLOW}Queue worker is not running. Starting...${NC}"
        start_worker
    fi

    echo ""
    check_pending_jobs
}

# Main script
case "${1:-check}" in
    status)
        show_status
        ;;
    start)
        start_worker
        ;;
    stop)
        stop_worker
        ;;
    restart)
        stop_worker
        sleep 1
        start_worker
        ;;
    check)
        check_and_start
        ;;
    logs)
        show_logs
        ;;
    *)
        echo "Usage: $0 {status|start|stop|restart|check|logs}"
        echo ""
        echo "Commands:"
        echo "  status  - Show detailed queue worker status"
        echo "  start   - Start the queue worker"
        echo "  stop    - Stop the queue worker"
        echo "  restart - Restart the queue worker"
        echo "  check   - Check and start if not running (default)"
        echo "  logs    - Show queue worker logs"
        exit 1
        ;;
esac
