#!/bin/bash

echo "🔍 DEBUGGING FILE UPLOAD ISSUE"
echo "==============================="

# Get token
TOKEN=$(curl -s -X POST https://api.rockvilletollandsda.church/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "Alright8-Reapply-Shrewdly-Platter-Important-Keenness-Banking-Streak-Tactile"}' \
  | jq -r '.data.token')

# Get bulletin ID
BULLETIN_ID=$(curl -s https://api.rockvilletollandsda.church/api/bulletins | jq -r '.data.items[0].id')
echo "Using bulletin ID: $BULLETIN_ID"

# Create test file
echo "Test PDF content for debugging" > debug_test.pdf

echo ""
echo "Testing file upload with verbose output..."
curl -v -X POST -H "Authorization: Bearer $TOKEN" \
  -F "file=@debug_test.pdf" \
  https://api.rockvilletollandsda.church/api/upload/bulletins/$BULLETIN_ID/pdf

echo ""
echo "Checking service logs for upload errors..."
sudo journalctl -u church-api.service -n 10 | tail -5

echo ""
echo "Testing file serve endpoint..."
curl -I https://api.rockvilletollandsda.church/api/upload/files/test.txt

# Cleanup
rm -f debug_test.pdf

echo ""
echo "Checking upload directory permissions..."
ls -la /opt/rtsda/church-api/uploads/
