#!/bin/bash

# Check if jq is installed
if ! command -v jq &> /dev/null; then
    echo "jq is required but not installed. Install it first."
    exit 1
fi

# Get Zitadel domain from ingress
ZITADEL_DOMAIN="zitadel.neptune.fourlights.dev"
echo "Zitadel Domain: $ZITADEL_DOMAIN"

# Read service account details
SA_USER_ID=$(jq -r '.userId' /tmp/zitadel-sa.json)
SA_KEY_ID=$(jq -r '.keyId' /tmp/zitadel-sa.json)

# Extract private key to a file
jq -r '.key' ./zitadel-admin-sa.json > /tmp/zitadel-private-key.pem

# Create JWT header and payload
HEADER=$(echo -n '{"alg":"RS256","typ":"JWT","kid":"'$SA_KEY_ID'"}' | base64 -w 0 | tr '+/' '-_' | tr -d '=')
NOW=$(date +%s)
EXP=$((NOW + 3600))  # 1 hour expiration

PAYLOAD=$(echo -n '{
  "iss": "'$SA_USER_ID'",
  "sub": "'$SA_USER_ID'",
  "aud": ["https://'$ZITADEL_DOMAIN'"],
  "exp": '$EXP',
  "iat": '$NOW'
}' | base64 -w 0 | tr '+/' '-_' | tr -d '=')

# Create signature
SIGNATURE=$(echo -n "${HEADER}.${PAYLOAD}" | openssl dgst -sha256 -sign /tmp/zitadel-private-key.pem | base64 -w 0 | tr '+/' '-_' | tr -d '=')

# Combine to create JWT
JWT="${HEADER}.${PAYLOAD}.${SIGNATURE}"

echo "JWT token generated!"
echo ""

# Exchange JWT for access token
echo "Exchanging JWT for access token..."
TOKEN_RESPONSE=$(curl -s -X POST "https://${ZITADEL_DOMAIN}/oauth/v2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" \
  -d "scope=openid profile email urn:zitadel:iam:org:project:id:zitadel:aud" \
  -d "assertion=${JWT}")

echo "Token Response:"
echo $TOKEN_RESPONSE | jq '.'

# Extract access token
ACCESS_TOKEN=$(echo $TOKEN_RESPONSE | jq -r '.access_token')

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

echo ""
echo "Testing healthz endpoint..."
# Test healthz endpoint
HEALTH_RESPONSE=$(curl -s -w "\nHTTP_STATUS:%{http_code}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  "https://${ZITADEL_DOMAIN}/management/v1/healthz")

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

echo "Health Check Response:"
echo "Status Code: $HTTP_STATUS"
echo "Body: $BODY"

# Clean up
rm -f /tmp/zitadel-sa.json /tmp/zitadel-private-key.pem

if [ "$HTTP_STATUS" == "200" ]; then
    echo ""
    echo "✅ Health check successful!"
else
    echo ""
    echo "❌ Health check failed!"
fi

