#!/bin/bash
# Script de migration automatique: handlers vers UUID
# Date: 2024-11-27

set -e

HANDLERS_DIR="veza-backend-api/internal/handlers"
BACKUP_DIR="veza-backend-api/internal/handlers/.backup-pre-uuid-migration"

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

mkdir -p "$BACKUP_DIR"
cp -r "$HANDLERS_DIR"/*.go "$BACKUP_DIR/" 2>/dev/null || true

FILES=$(find "$HANDLERS_DIR" -maxdepth 1 -name "*.go" -type f)

for filepath in $FILES; do
    filename=$(basename "$filepath")
    echo "🔄 $filename..."
    
    # Ajouter import uuid si absent
    if ! grep -q '"github.com/google/uuid"' "$filepath"; then
        sed -i '/^import (/a\	"github.com/google/uuid"' "$filepath" 2>/dev/null || true
    fi
    
    # Remplacer extraction userID du contexte:
    # userID := c.GetInt64("user_id") → userID := c.MustGet("user_id").(uuid.UUID)
    sed -i 's/userID := c\.GetInt64("user_id")/userID := c.MustGet("user_id").(uuid.UUID)/g' "$filepath"
    
    # Remplacer: userIDInterface.(int64) → userIDInterface.(uuid.UUID)
    sed -i 's/userIDInterface\.(int64)/userIDInterface.(uuid.UUID)/g' "$filepath"
    
    # Remplacer strconv.ParseInt(..., 10, 64) pour userID → uuid.Parse(...)
    sed -i 's/strconv\.ParseInt(\([^,]*\), 10, 64)/uuid.Parse(\1)/g' "$filepath"
    
    # Remplacer strconv.FormatInt(userID, 10) → userID.String()
    sed -i 's/strconv\.FormatInt(\([a-zA-Z_][a-zA-Z0-9_]*\), 10)/\1.String()/g' "$filepath"
    
    # Supprimer import strconv si plus utilisé après migration
    # (On laisse pour l'instant, sera nettoyé par goimports)
    
    echo "✅ $filename migré"
done

echo ""
echo "====================================="
echo "✅ Migration UUID Handlers terminée"
echo ""
echo "⚠️  Compiler: cd veza-backend-api && go build ./..."

