#!/bin/bash
# Script pour tester manuellement l'API Telnyx Detail Records

echo "╔═══════════════════════════════════════════════════════╗"
echo "║   Test Manual : Telnyx Detail Records API           ║"
echo "╚═══════════════════════════════════════════════════════╝"
echo ""

# Variables à configurer
TELNYX_API_KEY="${TELNYX_API_KEY:-YOUR_API_KEY_HERE}"
CALL_SESSION_ID="${1:-v3:your-call-session-id}"

if [ "$TELNYX_API_KEY" = "YOUR_API_KEY_HERE" ]; then
    echo "❌ ERROR: TELNYX_API_KEY not set!"
    echo ""
    echo "Usage:"
    echo "  export TELNYX_API_KEY=KEYxxxxxxxxxxx"
    echo "  ./test_telnyx_cost_api.sh v3:your-call-session-id"
    echo ""
    exit 1
fi

if [ "$CALL_SESSION_ID" = "v3:your-call-session-id" ]; then
    echo "❌ ERROR: CALL_SESSION_ID not provided!"
    echo ""
    echo "Usage:"
    echo "  ./test_telnyx_cost_api.sh v3:qg18_QgOdwtbMq9OkpQg2OxdR5Cb64sNte5kEA29czySKxS8TMAPEQ"
    echo ""
    exit 1
fi

echo "🔑 API Key: ${TELNYX_API_KEY:0:10}..."
echo "📞 Call Session ID: $CALL_SESSION_ID"
echo ""

echo "🚀 Calling Telnyx Detail Records API..."
echo ""

RESPONSE=$(curl -s -X GET \
  "https://api.telnyx.com/v2/detail_records?filter[call_session_id]=$CALL_SESSION_ID" \
  -H "Authorization: Bearer $TELNYX_API_KEY" \
  -H "Accept: application/json")

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X GET \
  "https://api.telnyx.com/v2/detail_records?filter[call_session_id]=$CALL_SESSION_ID" \
  -H "Authorization: Bearer $TELNYX_API_KEY" \
  -H "Accept: application/json")

echo "📡 HTTP Status: $HTTP_CODE"
echo ""

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ SUCCESS! Response:"
    echo "$RESPONSE" | jq '.'
    echo ""
    
    # Extract cost and duration
    COST=$(echo "$RESPONSE" | jq -r '.data[0].cost // "N/A"')
    DURATION=$(echo "$RESPONSE" | jq -r '.data[0].duration // "N/A"')
    START_TIME=$(echo "$RESPONSE" | jq -r '.data[0].start_time // "N/A"')
    
    echo "💰 Cost: $COST USD"
    echo "⏱️  Duration: $DURATION seconds"
    echo "🕐 Start Time: $START_TIME"
    echo ""
    
    if [ "$COST" = "N/A" ]; then
        echo "⚠️  WARNING: No cost data found!"
        echo "   Possible reasons:"
        echo "   - CDR not yet available (wait 2-5 minutes after call ends)"
        echo "   - Call session ID incorrect"
        echo ""
    fi
else
    echo "❌ FAILED! HTTP $HTTP_CODE"
    echo "$RESPONSE" | jq '.'
    echo ""
    
    if [ "$HTTP_CODE" = "401" ]; then
        echo "🔒 Unauthorized - API Key is invalid or expired"
    elif [ "$HTTP_CODE" = "404" ]; then
        echo "🔍 Not Found - Call session ID may be incorrect"
    fi
fi

echo "╔═══════════════════════════════════════════════════════╗"
echo "║                    Test Complete                     ║"
echo "╚═══════════════════════════════════════════════════════╝"
