#!/bin/bash
set -e

echo "🐳 Building and pushing Docker images to CitySensor registry..."

# Load configuration
if [ -f .env.registry ]; then
    export $(cat .env.registry | grep -v '^#' | xargs)
fi

# Default registry (CitySensor)
REGISTRY=${DOCKER_REGISTRY:-"docker.citysensor.de"}
NAMESPACE=${DOCKER_NAMESPACE:-""}
TAG=${IMAGE_TAG:-"latest"}

# Image names (with optional namespace)
if [ -n "$NAMESPACE" ]; then
    BACKEND_IMAGE="$REGISTRY/$NAMESPACE/rezepte-klaus-backend:$TAG"
    FRONTEND_IMAGE="$REGISTRY/$NAMESPACE/rezepte-klaus-frontend:$TAG"
else
    BACKEND_IMAGE="$REGISTRY/rezepte-klaus-backend:$TAG"
    FRONTEND_IMAGE="$REGISTRY/rezepte-klaus-frontend:$TAG"
fi

echo "📦 Building images..."
echo "Backend:  $BACKEND_IMAGE"
echo "Frontend: $FRONTEND_IMAGE"

# Login to CitySensor registry if credentials are provided
if [ -n "$DOCKER_USERNAME" ] && [ -n "$DOCKER_PASSWORD" ]; then
    echo "🔐 Logging into CitySensor registry..."
    echo "$DOCKER_PASSWORD" | docker login "$REGISTRY" -u "$DOCKER_USERNAME" --password-stdin
fi

# Build backend
echo "🔨 Building backend image..."
docker build -t "$BACKEND_IMAGE" ./nodejs-version/backend

# Build frontend (with production API URL)
echo "🔨 Building frontend image..."
if [ -n "$API_BASE_URL" ]; then
    docker build \
        --build-arg VITE_API_BASE_URL="$API_BASE_URL" \
        -t "$FRONTEND_IMAGE" \
        ./nodejs-version/frontend
else
    docker build \
        --build-arg VITE_API_BASE_URL="https://${DOMAIN:-yourdomain.com}/api" \
        -t "$FRONTEND_IMAGE" \
        ./nodejs-version/frontend
fi

# Push images
echo "📤 Pushing images to registry..."

if ! docker push "$BACKEND_IMAGE"; then
    echo "❌ Failed to push backend image. Make sure you're logged in to the registry:"
    echo "   CitySensor: echo \$DOCKER_PASSWORD | docker login docker.citysensor.de -u \$DOCKER_USERNAME --password-stdin"
    echo "   GitHub: echo \$GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin"
    echo "   Docker Hub: docker login"
    echo "   AWS ECR: aws ecr get-login-password --region REGION | docker login --username AWS --password-stdin ACCOUNT.dkr.ecr.REGION.amazonaws.com"
    exit 1
fi

if ! docker push "$FRONTEND_IMAGE"; then
    echo "❌ Failed to push frontend image."
    exit 1
fi

echo "✅ Successfully pushed images to registry!"
echo ""
echo "📋 Next steps:"
echo "1. Copy these files to your server:"
echo "   - docker-compose.registry.yml"
echo "   - .env.production (configured with your settings)"
echo "   - *.sql files"
echo "   - deploy-registry.sh"
echo ""
echo "2. On the server, update .env.production with:"
echo "   BACKEND_IMAGE=$BACKEND_IMAGE"
echo "   FRONTEND_IMAGE=$FRONTEND_IMAGE"
echo ""
echo "3. Run: ./deploy-registry.sh"