#!/bin/bash
# Script pour corriger automatiquement les erreurs UUID résiduelles
# Basé sur les erreurs de compilation identifiées
# Date: 2024-11-27

set -e

BACKEND_DIR="veza-backend-api/internal"

echo "🔧 Correction erreurs UUID résiduelles"
echo "======================================"

# 1. Corriger initialisations UUID
echo "🔄 Correction initialisations UUID (0 → uuid.Nil)..."
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/\(UserID:\s*\)0\s*,/\1uuid.Nil,/g' {} \;
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/\(OwnerID:\s*\)0\s*,/\1uuid.Nil,/g' {} \;
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/\(TrackID:\s*\)0\s*,/\1uuid.Nil,/g' {} \;

# 2. Corriger comparaisons UUID
echo "🔄 Correction comparaisons (== 0 → == uuid.Nil)..."
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/\([a-zA-Z_][a-zA-Z0-9_]*\)\.ID\s*==\s*0/\1.ID == uuid.Nil/g' {} \;
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/\([a-zA-Z_][a-zA-Z0-9_]*\)\.UserID\s*==\s*0/\1.UserID == uuid.Nil/g' {} \;

# 3. Corriger assignations
echo "🔄 Correction assignations (= 0 → = uuid.Nil)..."
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/\([a-zA-Z_][a-zA-Z0-9_]*ID\)\s*:=\s*0$/\1 := uuid.Nil/g' {} \;

# 4. Corriger time.Now().Unix() → uuid.New()
echo "🔄 Correction génération ID (Unix() → uuid.New())..."
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/time\.Now()\.Unix()/uuid.New()/g' {} \;

# 5. Corriger zap logs pour IDs qui sont maintenant UUID
echo "🔄 Correction logs zap pour struct fields..."
find "$BACKEND_DIR" -name "*.go" -exec sed -i \
    's/zap\.Int64("\([a-z_]*\)_id",\s*\([a-zA-Z_][a-zA-Z0-9_]*\)\.ID)/zap.String("\1_id", \2.ID.String())/g' {} \;

# 6. Corriger conversions int64() vers UUID
echo "🔄 Suppression int64() casts sur UUID..."
find "$BACKEND_DIR" -name "*.go" -exec sed -i 's/int64(\([a-zA-Z_][a-zA-Z0-9_]*\)\.ID)/\1.ID/g' {} \;

# 7. Ajouter imports uuid si manquants  
echo "🔄 Ajout imports uuid.UUID..."
for file in $(find "$BACKEND_DIR" -name "*.go"); do
    # Si le fichier utilise uuid.UUID mais n'importe pas le package
    if grep -q "uuid\.UUID\|uuid\.New\|uuid\.Nil\|uuid\.Parse" "$file" && ! grep -q '"github.com/google/uuid"' "$file"; then
        # Ajouter import
        sed -i '/^import (/a\	"github.com/google/uuid"' "$file" 2>/dev/null || \
        sed -i 's|^\(import.*"fmt"\)$|\1\n\t"github.com/google/uuid"|' "$file" 2>/dev/null || true
    fi
done

echo ""
echo "======================================"
echo "✅ Corrections automatiques terminées"
echo ""
echo "📝 Prochaines étapes:"
echo "1. go build ./..."
echo "2. Corriger manuellement erreurs restantes"
echo "3. go test ./..."

