#!/bin/bash

# @description Grubtech API Authentication - cURL
# @author Grubtech Integration Team
# @version 1.0.0
#
# This example demonstrates how to authenticate with the Grubtech API
# using an API key to obtain an access token.
#
# Prerequisites:
# - curl command-line tool
# - jq (for JSON parsing, optional but recommended)
# - Valid Grubtech API key
#
# Replace the following placeholders:
# - {{API_KEY}}: Your Grubtech API key
# - {{PARTNER_ID}}: Your partner identifier

API_KEY="{{API_KEY}}"
PARTNER_ID="{{PARTNER_ID}}"
BASE_URL="https://api.staging.grubtech.io"

# Authenticate with Grubtech API and obtain access token
authenticate() {
    echo "Authenticating with Grubtech API..."

    # Make authentication request
    RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
        "${BASE_URL}/v1/auth/token" \
        -H "Content-Type: application/json" \
        -H "x-api-key: ${API_KEY}" \
        -d "{
            \"partnerId\": \"${PARTNER_ID}\",
            \"grantType\": \"api_key\"
        }")

    # Extract HTTP status code and body
    HTTP_CODE=$(echo "$RESPONSE" | tail -n 1)
    BODY=$(echo "$RESPONSE" | sed '$d')

    # Check for errors
    if [ "$HTTP_CODE" -ne 200 ]; then
        echo "Authentication failed: HTTP $HTTP_CODE"
        echo "Response: $BODY"
        return 1
    fi

    # Extract token from response (using jq if available)
    if command -v jq &> /dev/null; then
        TOKEN=$(echo "$BODY" | jq -r '.token')
        EXPIRES_IN=$(echo "$BODY" | jq -r '.expiresIn')

        echo "Authentication successful!"
        echo "Token expires in: ${EXPIRES_IN} seconds"
    else
        # Fallback: manual parsing (less reliable)
        TOKEN=$(echo "$BODY" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
        echo "Authentication successful!"
        echo "Note: Install jq for better JSON parsing"
    fi

    echo "$TOKEN"
}

# Example: Use token in subsequent API requests
example_api_call() {
    local TOKEN=$1

    echo "Making example API call..."

    curl -s -X GET \
        "${BASE_URL}/v1/menus" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json"
}

# Main execution
main() {
    # Authenticate and get token
    ACCESS_TOKEN=$(authenticate)

    if [ -z "$ACCESS_TOKEN" ]; then
        echo "Failed to obtain access token"
        exit 1
    fi

    echo ""
    echo "Access Token: ${ACCESS_TOKEN:0:20}..."
    echo ""

    # Use token for API calls
    MENUS=$(example_api_call "$ACCESS_TOKEN")
    echo "Menus: $MENUS"
}

# Run main function
main
