#!/usr/bin/env bash
set -euo pipefail

APP_DIR="/var/www/html/insta_reels_downloads"
IMAGE="insta_reel_download:latest"
CONTAINER="insta_reel_download"
ENV_FILE="$APP_DIR/.env"

cd "$APP_DIR"

# Validate environment file
if [[ ! -f "$ENV_FILE" ]]; then
    echo "ERROR: Environment file not found: $ENV_FILE"
    exit 1
fi

echo "======================================"
echo " Updating source code..."
echo "======================================"

sudo git pull --ff-only origin login-flow-implement

echo "======================================"
echo " Building Docker image..."
echo "======================================"

sudo docker build -t "$IMAGE" .

echo "======================================"
echo " Running device platform migration..."
echo "======================================"

sudo docker run --rm \
    --entrypoint python3 \
    --env-file "$ENV_FILE" \
    "$IMAGE" \
    /app/scripts/migrate-device-platform.py

echo "======================================"
echo " Running authentication migration..."
echo "======================================"

sudo docker run --rm \
    --entrypoint python3 \
    --env-file "$ENV_FILE" \
    "$IMAGE" \
    /app/scripts/migrate-auth-tables.py

echo "======================================"
echo " Running payment migration..."
echo "======================================"

sudo docker run --rm \
    --entrypoint python3 \
    --env-file "$ENV_FILE" \
    "$IMAGE" \
    /app/scripts/migrate-payment-tables.py

echo "======================================"
echo " All migrations completed!"
echo "======================================"

# Replace container only after migrations succeed
echo "Stopping old container..."

sudo docker rm -f "$CONTAINER" 2>/dev/null || true

echo "======================================"
echo " Starting updated container..."
echo "======================================"

sudo docker run -d \
    --restart unless-stopped \
    --name "$CONTAINER" \
    --env-file "$ENV_FILE" \
    -p 9081:8000 \
    "$IMAGE"

sleep 5

echo "======================================"
echo " Container status"
echo "======================================"

sudo docker ps -a --filter "name=^/${CONTAINER}$"

echo "======================================"
echo " Recent container logs"
echo "======================================"

sudo docker logs --tail 100 "$CONTAINER"

# Verify container is running
if [[ "$(sudo docker inspect -f '{{.State.Running}}' "$CONTAINER")" != "true" ]]; then
    echo "ERROR: Container is not running!"
    exit 1
fi

echo "======================================"
echo " Deployment completed successfully!"
echo "======================================"
