#!/usr/bin/env bash

# Upload queue health cron job
# Schedule every 10 minutes to detect stalled uploads

set -euo pipefail

APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$APP_DIR"

LOG_DIR="$APP_DIR/storage/logs"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/cron-upload-queue-health.log"
LOCK_FILE="$LOG_DIR/upload_queue_health.lock"

exec 202>"$LOCK_FILE"
if ! flock -n 202; then
    exit 0
fi

timestamp() {
    date --iso-8601=seconds
}

echo "[$(timestamp)] Starting storage:check-upload-queues" >> "$LOG_FILE"
if /usr/bin/env php artisan storage:check-upload-queues --no-interaction --quiet >> "$LOG_FILE" 2>&1; then
    echo "[$(timestamp)] storage:check-upload-queues completed" >> "$LOG_FILE"
else
    status=$?
    echo "[$(timestamp)] storage:check-upload-queues failed (exit $status)" >> "$LOG_FILE"
    exit $status
fi
