#!/bin/bash
# Script de migration automatique: userID int64 → uuid.UUID dans tous les services
# Date: 2024-11-27
# Usage: ./scripts/migrate-services-to-uuid.sh

set -e

SERVICES_DIR="veza-backend-api/internal/services"
BACKUP_DIR="veza-backend-api/internal/services/.backup-pre-uuid-migration"

echo "🔧 Migration UUID Services - Début"
echo "===================================="

# Créer backup
echo "📦 Création backup dans $BACKUP_DIR..."
mkdir -p "$BACKUP_DIR"
cp -r "$SERVICES_DIR"/*.go "$BACKUP_DIR/" 2>/dev/null || true

# Trouver tous les fichiers Go dans services
FILES=$(find "$SERVICES_DIR" -maxdepth 1 -name "*.go" -type f)

for filepath in $FILES; do
    filename=$(basename "$filepath")
    
    # Skip files already migrated
    if [[ "$filename" == "jwt_service.go" ]] || [[ "$filename" == "auth_service.go" ]]; then
        echo "⏭️  $filename déjà migré (manuel), skip"
        continue
    fi
    
    echo "🔄 Migration de $filename..."
    
    # 1. Ajouter import uuid si absent
    if ! grep -q '"github.com/google/uuid"' "$filepath"; then
        # Trouver la ligne d'import et ajouter uuid
        sed -i '/^import (/a\	"github.com/google/uuid"' "$filepath" 2>/dev/null || \
        sed -i 's|"gorm.io/gorm"|"github.com/google/uuid"\n\t"gorm.io/gorm"|' "$filepath" 2>/dev/null || \
        sed -i 's|"veza-backend-api/internal/models"|"github.com/google/uuid"\n\t"veza-backend-api/internal/models"|' "$filepath" 2>/dev/null || true
    fi
    
    # 2. Remplacer paramètres de fonction: userID int64 → userID uuid.UUID
    sed -i 's/\([(,]\s*\)userID\s\+int64\s*\([,)]\)/\1userID uuid.UUID\2/g' "$filepath"
    
    # 3. Remplacer dans logs: zap.Int64("user_id", userID) → zap.String("user_id", userID.String())
    sed -i 's/zap\.Int64("user_id",\s*\([a-zA-Z_][a-zA-Z0-9_]*\))/zap.String("user_id", \1.String())/g' "$filepath"
    
    # 4. Remplacer dans logs: zap.Int64("owner_id", ownerID) → zap.String("owner_id", ownerID.String())
    sed -i 's/zap\.Int64("owner_id",\s*\([a-zA-Z_][a-zA-Z0-9_]*\))/zap.String("owner_id", \1.String())/g' "$filepath"
    
    # 5. Remplacer variables locales: var userID int64 → var userID uuid.UUID
    sed -i 's/var\s\+userID\s\+int64/var userID uuid.UUID/g' "$filepath"
    sed -i 's/var\s\+ownerID\s\+int64/var ownerID uuid.UUID/g' "$filepath"
    
    # 6. Remplacer dans structures: UserID: userID (int64) où userID est maintenant UUID
    # (Cette regexp est complexe, on va laisser les erreurs de compile nous guider après)
    
    echo "✅ $filename migré"
done

echo ""
echo "===================================="
echo "✅ Migration UUID Services terminée"
echo "📦 Backup: $BACKUP_DIR"
echo ""
echo "⚠️  PROCHAINES ÉTAPES:"
echo "1. Compiler: cd veza-backend-api && go build ./..."
echo "2. Corriger erreurs manuellement (conversions restantes)"
echo "3. Tester: go test ./..."

