#!/bin/bash

echo "🔍 COMPREHENSIVE FILE UPLOAD DEBUG"
echo "=================================="

# From your previous debug, we know the file was uploaded as:
UPLOADED_FILE="03378cc5-8c62-48b6-818e-643588b253ce.pdf"
UPLOAD_DIR="/opt/rtsda/church-api/uploads/bulletins"
API_BASE="https://api.rockvilletollandsda.church"

echo "📁 Step 1: Check if uploaded file actually exists"
echo "Looking for: $UPLOAD_DIR/$UPLOADED_FILE"
if [ -f "$UPLOAD_DIR/$UPLOADED_FILE" ]; then
    echo "✅ File exists!"
    ls -la "$UPLOAD_DIR/$UPLOADED_FILE"
    echo "File size: $(du -h "$UPLOAD_DIR/$UPLOADED_FILE" | cut -f1)"
else
    echo "❌ File NOT found!"
    echo "Contents of bulletins directory:"
    ls -la "$UPLOAD_DIR/"
fi

echo ""
echo "📡 Step 2: Test different file serve URL patterns"
echo "Testing various possible endpoints..."

# Test common patterns for file serving
ENDPOINTS=(
    "/uploads/bulletins/$UPLOADED_FILE"
    "/api/uploads/bulletins/$UPLOADED_FILE" 
    "/api/files/bulletins/$UPLOADED_FILE"
    "/static/uploads/bulletins/$UPLOADED_FILE"
    "/files/bulletins/$UPLOADED_FILE"
    "/bulletins/$UPLOADED_FILE"
)

for endpoint in "${ENDPOINTS[@]}"; do
    echo "Testing: $API_BASE$endpoint"
    response=$(curl -s -o /dev/null -w "%{http_code}" "$API_BASE$endpoint")
    echo "Response: $response"
    if [ "$response" != "404" ]; then
        echo "🎉 FOUND WORKING ENDPOINT: $endpoint"
        break
    fi
done

echo ""
echo "🔧 Step 3: Check API server configuration"
echo "Looking for static file serving configuration..."

# Check if there's a Rust Cargo.toml or main.rs that might show routing
echo "Checking for Rust project files:"
find /opt/rtsda/church-api -name "Cargo.toml" -o -name "main.rs" -o -name "lib.rs" | head -5

echo ""
echo "🌐 Step 4: Check Caddy configuration"
echo "Caddy reverse proxy might need static file rules..."
if [ -f "/etc/caddy/Caddyfile" ]; then
    echo "Found Caddyfile, checking for static file rules:"
    grep -n -A5 -B5 "file_server\|root\|static" /etc/caddy/Caddyfile || echo "No static file serving rules found"
else
    echo "No Caddyfile found at /etc/caddy/Caddyfile"
    echo "Checking other common locations:"
    find /etc -name "*caddy*" -type f 2>/dev/null | head -5
fi

echo ""
echo "📋 Step 5: Check API server logs for file access attempts"
echo "Recent logs when accessing files:"
journalctl -u church-api.service --since "10 minutes ago" | tail -20

echo ""
echo "🔍 Step 6: Test with a simple file serve"
echo "Let's see what the API returns when we try to access the file:"
echo "Full response headers and body:"
curl -v "$API_BASE/uploads/bulletins/$UPLOADED_FILE" 2>&1

echo ""
echo "💡 SUMMARY & NEXT STEPS:"
echo "Based on the results above, we need to:"
echo "1. Confirm the file exists and has correct permissions"
echo "2. Find the correct endpoint pattern for serving files"
echo "3. Check if static file serving is configured in your API server"
echo "4. Verify Caddy is properly proxying static file requests"
