#!/bin/bash
set -e

BASE_URL="http://localhost:5000"
TOKEN="${JSON_ENGINE_AUTH_TOKEN:-dev-token-change-in-prod}"

echo "=========================================="
echo "JSON Engine Smoke Test (Rust)"
echo "=========================================="

# Test /health
echo -e "\n[1/6] Testing /health..."
curl -s "$BASE_URL/health" | jq . || exit 1
echo "✓ Health OK"

# Test auth requis (401)
echo -e "\n[2/6] Testing auth requirement (401)..."
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$BASE_URL/collect/engine_execution" \
  -H "Content-Type: application/json" \
  -d '{"schema_version":"1.0.0"}')
if [ "$STATUS" = "401" ]; then
  echo "✓ Auth protection OK (401)"
else
  echo "✗ Expected 401, got $STATUS"
  exit 1
fi

# Test mauvais token (403)
echo -e "\n[3/6] Testing wrong token (403)..."
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$BASE_URL/collect/engine_execution" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wrong-token" \
  -d '{"schema_version":"1.0.0"}')
if [ "$STATUS" = "403" ]; then
  echo "✓ Invalid token rejected (403)"
else
  echo "✗ Expected 403, got $STATUS"
  exit 1
fi

# Test engine_execution (202)
echo -e "\n[4/6] Testing /collect/engine_execution (202)..."
TRACE_ID=$(uuidgen)
curl -s -X POST "$BASE_URL/collect/engine_execution" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "schema_version": "1.0.0",
    "trace_id": "'$TRACE_ID'",
    "task_id": "task-'$(date +%s)'",
    "engine_id": "rust_engine",
    "engine_instance_id": "rust-test-1",
    "timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
    "input": {"type": "code", "content": "fn main() {}", "language": "rust"},
    "output": {"type": "result", "content": "compiled"},
    "metrics": {"latency_ms": 42.5, "success": true, "memory_mb": 30.0, "cpu_percent": 15.0},
    "status": "completed",
    "quality_score": 0.93
  }' | jq . || exit 1
echo "✓ Engine execution accepted"

# Test payload invalide (400)
echo -e "\n[5/6] Testing invalid payload (400)..."
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$BASE_URL/collect/engine_execution" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"schema_version":"1.0.0","trace_id":"abc"}')
if [ "$STATUS" = "400" ]; then
  echo "✓ Invalid payload rejected (400)"
else
  echo "✗ Expected 400, got $STATUS"
  exit 1
fi

# Test /stats
echo -e "\n[6/6] Testing /stats..."
curl -s "$BASE_URL/stats" | jq . || exit 1
echo "✓ Stats OK"

echo -e "\n=========================================="
echo "✓ All tests passed!"
echo "=========================================="
