#!/bin/bash

echo "=== Testing Agencies Endpoint ==="
echo ""

# Get a fresh token
echo "1. Getting token..."
TOKEN=$(curl -s -X POST "http://localhost:8080/realms/b2b-flight-platform/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=superadmin" \
  -d "password=admin123" \
  -d "grant_type=password" \
  -d "client_id=b2b-flight-backend" \
  -d "client_secret=b2b-flight-backend-secret" | jq -r '.access_token')

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

echo "Token obtained successfully"
echo ""

# Test the endpoint
echo "2. Testing GET /api/v1/agencies..."
echo ""
RESPONSE=$(curl -s -w "\nHTTP_STATUS:%{http_code}" -X GET "http://localhost:8081/api/v1/agencies" \
  -H "accept: application/json" \
  -H "Authorization: Bearer $TOKEN")

HTTP_STATUS=$(echo "$RESPONSE" | grep "HTTP_STATUS:" | cut -d: -f2)
BODY=$(echo "$RESPONSE" | sed '/HTTP_STATUS:/d')

echo "Status Code: $HTTP_STATUS"
echo ""
echo "Response Body:"
echo "$BODY" | jq '.' 2>/dev/null || echo "$BODY"

echo ""
if [ "$HTTP_STATUS" = "200" ]; then
    echo "✅ SUCCESS! The endpoint is working correctly."
else
    echo "❌ FAILED with status $HTTP_STATUS"
fi
