#!/usr/bin/env fish

echo "🖼️ DIRECT FILE COPY + PROPER UPDATE"
echo "==================================="

set API_BASE "https://api.rockvilletollandsda.church/api"
set STORAGE_PATH "/media/archive/pocketbase-temp/pocketbase/pb_data/storage/2tz9osuik53a0yh"
set OLD_PB_BASE "https://pocketbase.rockvilletollandsda.church/api"
set UPLOAD_DIR "/opt/rtsda/church-api/uploads/events"

# Get token
set AUTH_RESPONSE (curl -s -X POST $API_BASE/auth/login \
    -H "Content-Type: application/json" \
    -d '{"username": "admin", "password": "Alright8-Reapply-Shrewdly-Platter-Important-Keenness-Banking-Streak-Tactile"}')

set JWT_TOKEN (echo $AUTH_RESPONSE | jq -r '.data.token')
echo "✅ Got token"

# Get events for matching
set NEW_EVENTS (curl -s -H "Authorization: Bearer $JWT_TOKEN" "$API_BASE/events?perPage=500")
echo $NEW_EVENTS | jq '.data.items | map({id, title})' > new_events.json

set OLD_EVENTS (curl -s "$OLD_PB_BASE/collections/events/records?perPage=500")
echo $OLD_EVENTS | jq '.items | map({id, title})' > old_events.json

set uploaded 0
set failed 0

for event_dir in (find $STORAGE_PATH -mindepth 1 -maxdepth 1 -type d -name '[a-z0-9]*')
    set old_id (basename $event_dir)
    set image_file (find $event_dir -maxdepth 1 -name "*.webp" -type f | head -1)
    
    if test -z "$image_file"
        continue
    end
    
    # Get old event and find new match
    set old_event (cat old_events.json | jq --arg id "$old_id" '.[] | select(.id == $id)')
    if test -z "$old_event"
        continue
    end
    
    set title (echo $old_event | jq -r '.title')
    set new_event (cat new_events.json | jq --arg title "$title" '.[] | select(.title == $title)')
    
    if test -z "$new_event"
        echo "❌ No match for: $title"
        continue
    end
    
    set new_id (echo $new_event | jq -r '.id')
    set filename (basename $image_file)
    set new_filename "$new_id-$filename"
    set image_path "uploads/events/$new_filename"
    
    echo "📤 Processing: $title"
    
    # Copy file to upload directory
    cp "$image_file" "$UPLOAD_DIR/$new_filename"
    
    if test $status -eq 0
        echo "✅ File copied: $new_filename"
        
        # Get current event data first
        set current_event (curl -s -H "Authorization: Bearer $JWT_TOKEN" \
            "$API_BASE/events/$new_id")
        
        # Extract current event data and add image path
        set event_data (echo $current_event | jq --arg img "$image_path" \
            '.data | {
                title: .title,
                description: .description,
                start_time: .start_time,
                end_time: .end_time,
                location: .location,
                location_url: .location_url,
                category: .category,
                recurring_type: .recurring_type,
                is_featured: .is_featured,
                image: $img
            }')
        
        # Update event with complete data
        set update_response (curl -s -X PUT \
            -H "Authorization: Bearer $JWT_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$event_data" \
            "$API_BASE/admin/events/$new_id")
        
        set success (echo $update_response | jq -r '.success // false')
        
        if test "$success" = "true"
            echo "✅ SUCCESS: $title"
            set uploaded (math $uploaded + 1)
        else
            echo "❌ DB UPDATE FAILED: $title"
            echo "   Response: "(echo $update_response)
            set failed (math $failed + 1)
        end
    else
        echo "❌ FILE COPY FAILED: $title"
        set failed (math $failed + 1)
    end
    
    echo "---"
    sleep 0.1
end

rm -f new_events.json old_events.json

echo ""
echo "🎉 FINAL RESULTS!"
echo "================="
echo "✅ Successfully uploaded: $uploaded images"
echo "❌ Failed uploads: $failed images"
echo ""
echo "🌐 Images should be accessible at: https://api.rockvilletollandsda.church/uploads/events/"
