#!/bin/sh

# Default path if not passed as argument
PROJECT_PATH="${1:-/var/www/html/server}"
LOG_FILE="$PROJECT_PATH/queues/queues.log"

cd "$PROJECT_PATH" || { echo "Invalid path: $PROJECT_PATH"; exit 1; }

# Base artisan queue command
ARTISAN="php artisan queue:work --daemon --delay=30"

# Function to start a queue if not already running
start_queue_if_not_running() {
  QUEUE_NAME="$1"
  CONNECTION="$2"

  if ! pgrep -f "queue:work.*--queue=${QUEUE_NAME}" > /dev/null; then
    echo "$(date): Starting queue: $QUEUE_NAME" >> "$LOG_FILE"
    $ARTISAN "$CONNECTION" --queue="$QUEUE_NAME" >> "$LOG_FILE" 2>&1 &
  else
    echo "$(date): Already running: $QUEUE_NAME" >> "$LOG_FILE"
  fi
}

# List of queues to monitor/start
start_queue_if_not_running "sendemail" "jobs_emails"
start_queue_if_not_running "updatequeuingloanborrowliststatustoworkinprogress" "jobs_loan_borrow_lists"
start_queue_if_not_running "updatequeuingloanborrowliststatustoworkdone" "jobs_loan_borrow_lists"
start_queue_if_not_running "notifyworkerrequest" "jobs_loan_borrow_lists"
start_queue_if_not_running "updatesearch" "jobs_loan_borrow_lists"
start_queue_if_not_running "updateexpiredmonthlysubscription" "jobs_subscriptions"
start_queue_if_not_running "updateexpiredsubscription" "jobs_subscriptions"
start_queue_if_not_running "updateblockedsubscription" "jobs_subscriptions"
start_queue_if_not_running "deleteunsubmittedcompanycart" "jobs_carts"
start_queue_if_not_running "searchremovepastdates" "jobs_carts"
start_queue_if_not_running "declinequeuingexpiredloanrequest" "jobs_expired_requests"
start_queue_if_not_running "sendsmsreminders" "jobs_sms_reminders"
start_queue_if_not_running "companycsvimport" "jobs_imports"
