#!/bin/bash
# Helper script to exchange Podchaser client credentials for an access token

if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage: $0 <client_id> <client_secret>"
    echo ""
    echo "Example:"
    echo "  $0 'your-client-id' 'your-client-secret'"
    echo ""
    echo "Get your credentials from: https://www.podchaser.com/creators/dashboard/api"
    exit 1
fi

CLIENT_ID="$1"
CLIENT_SECRET="$2"

echo "Exchanging Podchaser credentials for access token..."

RESPONSE=$(curl -s -X POST "https://api.podchaser.com/graphql" \
  -H "Content-Type: application/json" \
  -d "{\"query\": \"mutation { requestAccessToken(input: { grant_type: CLIENT_CREDENTIALS client_id: \\\"$CLIENT_ID\\\" client_secret: \\\"$CLIENT_SECRET\\\" }) { access_token } }\"}")

# Check for errors
if echo "$RESPONSE" | jq -e '.errors' > /dev/null 2>&1; then
    echo "❌ Error getting access token:"
    echo "$RESPONSE" | jq -r '.errors[].message'
    exit 1
fi

# Extract access token
ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r '.data.requestAccessToken.access_token')

if [ -z "$ACCESS_TOKEN" ] || [ "$ACCESS_TOKEN" = "null" ]; then
    echo "❌ Failed to get access token. Response:"
    echo "$RESPONSE" | jq '.'
    exit 1
fi

echo ""
echo "✅ Success! Your Podchaser access token:"
echo ""
echo "$ACCESS_TOKEN"
echo ""
echo "This token is valid for 1 year."
echo "Copy this token and paste it into Configuration > Appearances > Podchaser API Key"
