#!/usr/bin/env bash
set -euo pipefail

usage() {
    cat <<'USAGE'
Usage:
  Add B3_CLIENT_ID and B3_CLIENT_SECRET to the project .env file, then run:
    ./test/b3_credentials_check.sh

The script:
  1. Loads credentials from ../.env
  2. Requests an OAuth token via Client Credentials (prod URL)
  3. Calls the prod healthcheck endpoint with the token

Both endpoints are hardcoded to the production environment.
USAGE
}

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_ROOT=$(cd "$SCRIPT_DIR/.." && pwd)
ENV_FILE="$PROJECT_ROOT/.env"

parse_env_value() {
    local key="$1"
    if [[ ! -f "$ENV_FILE" ]]; then
        return
    fi
    sed -n "s/^${key}=//p" "$ENV_FILE" | tail -n1 | tr -d '\r'
}

B3_CLIENT_ID=$(parse_env_value "B3_CLIENT_ID")
B3_CLIENT_SECRET=$(parse_env_value "B3_CLIENT_SECRET")

if [[ -z "$B3_CLIENT_ID" || -z "$B3_CLIENT_SECRET" ]]; then
    echo "[error] B3_CLIENT_ID and B3_CLIENT_SECRET must be defined in .env" >&2
    usage
    exit 1
fi

B3_AUTH_URL="https://apib3i.b3.com.br/auth/oauth/v2/token"
B3_HEALTHCHECK_URL="https://apib3i.b3.com.br/api/healthcheck/{token}"

echo "[info] Requesting OAuth token from $B3_AUTH_URL"
TOKEN_RESPONSE=$(curl --silent --show-error --fail \
    -u "$B3_CLIENT_ID:$B3_CLIENT_SECRET" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d 'grant_type=client_credentials' \
    "$B3_AUTH_URL")

TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.access_token // empty')

if [[ -z "$TOKEN" ]]; then
    echo "[error] Failed to extract access_token from response:" >&2
    echo "$TOKEN_RESPONSE" >&2
    exit 1
fi

echo "[info] Token retrieved successfully"

HEALTH_URL=${B3_HEALTHCHECK_URL//\{token\}/$TOKEN}
echo "[info] Calling healthcheck at $HEALTH_URL"

HEALTH_RESPONSE=$(curl --silent --show-error --fail "$HEALTH_URL")

echo "[info] Healthcheck response:"
echo "$HEALTH_RESPONSE" | jq .
