#!/bin/bash
# O11Y Auth0 Token Manager
# Usage: source scripts/o11y-token.sh && get_o11y_token

ENV_FILE="${ENV_FILE:-.env}"

get_o11y_token() {
    # Load .env
    if [ -f "$ENV_FILE" ]; then
        source "$ENV_FILE"
    else
        echo "ERROR: $ENV_FILE not found" >&2
        return 1
    fi

    # Check if we have a valid cached token
    local now=$(date +%s)
    
    if [ -n "$O11Y_AUTH0_TOKEN" ] && [ -n "$O11Y_AUTH0_TOKEN_EXPIRES" ]; then
        # Token exists, check if it's still valid (with 5 min buffer)
        local expires_with_buffer=$((O11Y_AUTH0_TOKEN_EXPIRES - 300))
        if [ "$now" -lt "$expires_with_buffer" ]; then
            echo "Using cached token (expires in $((O11Y_AUTH0_TOKEN_EXPIRES - now))s)" >&2
            echo "$O11Y_AUTH0_TOKEN"
            return 0
        fi
        echo "Token expired or expiring soon, fetching new one..." >&2
    else
        echo "No cached token found, fetching new one..." >&2
    fi

    # Fetch new token
    local response=$(curl -s 'https://tidb-soc2.us.auth0.com/oauth/token' \
        -H 'content-type: application/x-www-form-urlencoded' \
        -d 'grant_type=client_credentials' \
        -d "client_id=${O11Y_CLIENT_ID}" \
        -d "client_secret=${O11Y_CLIENT_SECRET}" \
        -d 'audience=https://tidb-soc2.us.auth0.com/api/v2/')

    local token=$(echo "$response" | jq -r '.access_token')
    local expires_in=$(echo "$response" | jq -r '.expires_in')

    if [ -z "$token" ] || [ "$token" = "null" ]; then
        echo "ERROR: Failed to get Auth0 token" >&2
        echo "$response" >&2
        return 1
    fi

    # Calculate expiration timestamp
    local expires_at=$((now + expires_in))

    # Update .env file
    # Remove old token lines if they exist
    grep -v "^O11Y_AUTH0_TOKEN=" "$ENV_FILE" | grep -v "^O11Y_AUTH0_TOKEN_EXPIRES=" > "${ENV_FILE}.tmp"
    
    # Add new token lines
    echo "O11Y_AUTH0_TOKEN=${token}" >> "${ENV_FILE}.tmp"
    echo "O11Y_AUTH0_TOKEN_EXPIRES=${expires_at}" >> "${ENV_FILE}.tmp"
    
    mv "${ENV_FILE}.tmp" "$ENV_FILE"

    echo "New token fetched, expires in ${expires_in}s (at $(date -r $expires_at 2>/dev/null || date -d @$expires_at))" >&2
    echo "$token"
}

# Export function for use in subshells
export -f get_o11y_token
