#!/bin/bash

# HDNABI REST API Test Script
# Usage: ./test.sh

API_URL="http://localhost:3001"
API_KEY="test_api_key_12345"
API_SECRET="test_api_secret_67890"

echo "============================================"
echo "HDNABI REST API Test Suite"
echo "============================================"

# Test 1: Health Check
echo -e "\n[1/7] Health Check"
echo "GET /health"
curl -s -X GET $API_URL/health | jq
sleep 1

# Test 2: Get Token
echo -e "\n[2/7] Get Authentication Token"
echo "POST /api/v1/auth/token"
TOKEN_RESPONSE=$(curl -s -X POST $API_URL/api/v1/auth/token \
  -H "x-api-key: $API_KEY" \
  -H "x-api-secret: $API_SECRET")

echo "$TOKEN_RESPONSE" | jq

TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.token')

if [ "$TOKEN" == "null" ] || [ -z "$TOKEN" ]; then
  echo "❌ Failed to get token. Exiting."
  exit 1
fi

echo "✅ Token obtained: ${TOKEN:0:20}..."
sleep 1

# Test 3: List Assets
echo -e "\n[3/7] List Assets"
echo "GET /api/v1/assets/list"
curl -s -X GET $API_URL/api/v1/assets/list \
  -H "Authorization: Bearer $TOKEN" | jq
sleep 1

# Test 4: Get Telemetry Data (No time_from)
echo -e "\n[4/7] Get Telemetry Data (Last 10 minutes)"
echo "GET /api/v1/assets"
TELEMETRY_RESPONSE=$(curl -s -X GET $API_URL/api/v1/assets \
  -H "Authorization: Bearer $TOKEN")

echo "$TELEMETRY_RESPONSE" | jq

TIME_TO=$(echo "$TELEMETRY_RESPONSE" | jq -r '.time_to')
sleep 1

# Test 5: Get Telemetry Data (With time_from)
echo -e "\n[5/7] Get Telemetry Data (Delta Window)"
echo "GET /api/v1/assets?time_from=$TIME_TO"
curl -s -X GET "$API_URL/api/v1/assets?time_from=$TIME_TO" \
  -H "Authorization: Bearer $TOKEN" | jq
sleep 1

# Test 6: Exclude Asset
echo -e "\n[6/7] Exclude Asset"
echo "POST /api/v1/assets/exclude"
curl -s -X POST $API_URL/api/v1/assets/exclude \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"vins": ["VIN1234567890ABCDE"]}' | jq
sleep 1

# Test 7: Include Asset
echo -e "\n[7/7] Include Asset"
echo "POST /api/v1/assets/include"
curl -s -X POST $API_URL/api/v1/assets/include \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"vins": ["VIN1234567890ABCDE"]}' | jq

echo -e "\n============================================"
echo "✅ Test Suite Complete"
echo "============================================"
