#!/bin/sh
# tests/mock_refresh.sh - stand-in for scorpiox-copilot-refreshtoken.
#
# The real CLI derives the short-lived Copilot JWT from the stored github_token
# and caches it in ~/.copilot/.copilot-token-cache.json, then prints the JWT on
# stdout. The plugin must discard that stdout entirely and prove the refresh by
# re-reading the cache file, so this mock prints a deliberately leaky payload to
# make a regression visible in the tests.
#
#   --credentials-file <path> [--force]
#
# COPILOT_MOCK_FAIL=1 makes the refresh fail without touching the cache.

set -u

CREDS=""
while [ $# -gt 0 ]; do
    case "$1" in
        --credentials-file) shift; CREDS="$1" ;;
        *) : ;;
    esac
    shift
done

[ -n "$CREDS" ] || CREDS="${COPILOT_CREDS_PATH:-$HOME/.copilot/.credentials.json}"

if [ ! -f "$CREDS" ]; then
    printf 'error: cannot read credentials file: %s\n' "$CREDS" >&2
    exit 1
fi

if [ "${COPILOT_MOCK_FAIL:-0}" = "1" ]; then
    printf 'error: token exchange failed\n' >&2
    exit 1
fi

case "$CREDS" in
    */.copilot/.credentials.json) D=$(dirname "$CREDS") ;;
    *) D=$(dirname "$CREDS") ;;
esac
CACHE="$D/.copilot-token-cache.json"

EXP=$(( $(date +%s) + 1800 ))
{
    printf '{"access_token": "MOCK-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$EXP"
} > "$CACHE"

# Exactly what the real CLI prints: token material on stdout. The plugin reads
# this and throws it away.
printf 'Token exchange successful\n'
printf '{"access_token": "MOCK-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$EXP"
exit 0
