#!/bin/bash
set -e

VERSION=${1:-latest}
IMAGE="gitea.tenhal.sa/marwan/hh:${VERSION}"

echo "========================================"
echo "  PX360 Staging Deploy"
echo "  Image: $IMAGE"
echo "  $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"

echo ""
echo "[1/6] Pulling new image..."
docker pull "$IMAGE" || {
    echo "ERROR: Failed to pull image $IMAGE"
    exit 1
}

echo ""
echo "[2/6] Running pre-flight checks..."
docker run --rm --env-file .env.staging "$IMAGE" python manage.py check --deploy || {
    echo "ERROR: Pre-flight checks failed. Aborting."
    exit 1
}

echo ""
echo "[3/6] Running migrations..."
docker run --rm --env-file .env.staging --network px360_net "$IMAGE" python manage.py migrate --noinput || {
    echo "ERROR: Migrations failed. Aborting deploy."
    exit 1
}

echo ""
echo "[4/6] Collecting static files..."
export PX360_IMAGE="$IMAGE"
docker compose -f docker-compose.staging.yml run --rm --no-deps web python manage.py collectstatic --noinput

echo ""
echo "[5/6] Restarting all services with new image..."
docker compose -f docker-compose.staging.yml up -d --remove-orphans --force-recreate

echo ""
echo "[6/6] Cleaning up old images..."
docker image prune -f

echo ""
echo "========================================"
echo "  Staging deploy complete!"
echo "  Version: $VERSION"
echo "========================================"
echo ""
docker compose -f docker-compose.staging.yml ps
echo ""
echo "Logs: docker compose -f docker-compose.staging.yml logs -f"
echo "Stop:  docker compose -f docker-compose.staging.yml down"
echo "Rollback: ./deploy.staging.sh <previous-version>"
