#!/usr/bin/env fish
echo "🔧 FIXING API TO SUPPORT IMAGE_PATH UPDATES"
echo "============================================"

# Check if we're in the right directory
if not test -f "src/models.rs"
    echo "❌ Error: src/models.rs not found. Are you in the church-api directory?"
    exit 1
end

echo "1️⃣ Backing up original files..."
cp src/models.rs src/models.rs.backup
cp src/db/events.rs src/db/events.rs.backup
echo "✅ Backups created: .backup files"

echo "2️⃣ Adding image_path to CreateEventRequest struct..."
sed -i 's/pub recurring_type: Option<String>,/pub recurring_type: Option<String>,\n    pub image_path: Option<String>,/' src/models.rs

if grep -q "pub image_path: Option<String>," src/models.rs
    echo "✅ Added image_path field to CreateEventRequest"
else
    echo "❌ Failed to add image_path field"
    exit 1
end

echo "3️⃣ Updating database update function..."
# Replace the UPDATE query to include image_path
sed -i 's/recurring_type = $9, updated_at = NOW()/recurring_type = $9, image_path = $10, updated_at = NOW()/' src/db/events.rs
sed -i 's/WHERE id = $10/WHERE id = $11/' src/db/events.rs
sed -i '/req.recurring_type,/a\        req.image_path,' src/db/events.rs

if grep -q "image_path = \$10" src/db/events.rs
    echo "✅ Updated database function"
else
    echo "❌ Failed to update database function"
    exit 1
end

echo "4️⃣ Building the project..."
if cargo build
    echo "✅ Build successful!"
else
    echo "❌ Build failed! Restoring backups..."
    cp src/models.rs.backup src/models.rs
    cp src/db/events.rs.backup src/db/events.rs
    exit 1
end

echo "5️⃣ Showing changes made..."
echo ""
echo "=== Changes to src/models.rs ==="
diff src/models.rs.backup src/models.rs || true
echo ""
echo "=== Changes to src/db/events.rs ==="
diff src/db/events.rs.backup src/db/events.rs || true

echo ""
echo "🎉 SUCCESS!"
echo "============"
echo "✅ Added image_path field to CreateEventRequest struct"
echo "✅ Updated database update function to handle image_path"
echo "✅ Project compiled successfully"
echo ""
echo "🚀 Next steps:"
echo "1. Restart your API server"
echo "2. Run your image_path update script"
echo "3. Images should now load properly!"
echo ""
echo "💾 Backup files saved as:"
echo "   - src/models.rs.backup"
echo "   - src/db/events.rs.backup"
