#!/usr/bin/env fish

echo "🖼️ DIRECT FILE COPY + PATH UPDATE (DEBUG)"
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

# Test with just ONE event to see the actual API response
set test_dir (find $STORAGE_PATH -mindepth 1 -maxdepth 1 -type d -name '[a-z0-9]*' | head -1)
set old_id (basename $test_dir)
set image_file (find $test_dir -maxdepth 1 -name "*.webp" -type f | head -1)

set old_event (cat old_events.json | jq --arg id "$old_id" '.[] | select(.id == $id)')
set title (echo $old_event | jq -r '.title')
set new_event (cat new_events.json | jq --arg title "$title" '.[] | select(.title == $title)')
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 "🧪 Testing with: $title"
echo "Image path: $image_path"

# Copy file
cp "$image_file" "$UPLOAD_DIR/$new_filename"
echo "✅ File copied"

# Test the API update with debug
echo "📤 Testing API update..."
set update_response (curl -s -w "\nHTTP_CODE:%{http_code}\nCONTENT_TYPE:%{content_type}\n" \
    -X PUT \
    -H "Authorization: Bearer $JWT_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"image\": \"$image_path\"}" \
    "$API_BASE/admin/events/$new_id")

echo "RAW API RESPONSE:"
echo "$update_response"

echo ""
echo "🔍 Checking if file is accessible..."
curl -I "https://api.rockvilletollandsda.church/$image_path"

rm -f new_events.json old_events.json
