#!/bin/bash
# Synchronisiert Versionsnummer über das gesamte Projekt

set -e

# Farben für Output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Hole Version aus frontend/package.json (als Single Source of Truth)
FRONTEND_VERSION=$(node -p "require('./frontend/package.json').version")

echo -e "${BLUE}📦 Synchronisiere Version: ${GREEN}${FRONTEND_VERSION}${NC}"

# 1. Backend package.json aktualisieren
echo "  ├─ Backend package.json..."
cd backend
npm version $FRONTEND_VERSION --no-git-tag-version --allow-same-version
cd ..

# 2. OpenAPI generate-openapi.js aktualisieren
echo "  ├─ Backend OpenAPI Spec..."
sed -i "s/version: '[0-9]\+\.[0-9]\+\.[0-9]\+'/version: '${FRONTEND_VERSION}'/" backend/src/generate-openapi.js

# 2. Docker Compose Files (optional, falls vorhanden)
if [ -f "docker/prod/docker-compose.yml" ]; then
    echo "  ├─ Docker Compose (prod)..."
    sed -i "s/image: hobbyhimmel\/image-uploader-frontend:[0-9]\+\.[0-9]\+\.[0-9]\+/image: hobbyhimmel\/image-uploader-frontend:${FRONTEND_VERSION}/" docker/prod/docker-compose.yml || true
    sed -i "s/image: hobbyhimmel\/image-uploader-backend:[0-9]\+\.[0-9]\+\.[0-9]\+/image: hobbyhimmel\/image-uploader-backend:${FRONTEND_VERSION}/" docker/prod/docker-compose.yml || true
fi

# 3. OpenAPI Spec neu generieren
echo "  ├─ Regeneriere OpenAPI Spec..."
cd backend
npm run generate-openapi > /dev/null 2>&1
cd ..

echo -e "${GREEN}✓ Alle Versionen auf ${FRONTEND_VERSION} synchronisiert!${NC}"
