#!/usr/bin/env bash
# Generate a JWT token for testing Lendair API calls.
# Usage: ./scripts/create_test_token <user-id> [secret-env-var]
#
# Reads the JWT secret from the environment (default: CLERK_SECRET_KEY).
# Falls back to .env file in the project root.
#
# Example:
#   CLERK_SECRET_KEY=sk_test_xxx ./scripts/create_test_token user_123
#   ./scripts/create_test_token user_123 CLERK_SECRET_KEY

set -euo pipefail

if [ $# -lt 1 ]; then
  echo "Usage: $(basename "$0") <user-id> [secret-env-var]" >&2
  echo "" >&2
  echo "Generates a JWT token with the given user-id as subject." >&2
  echo "The secret is read from the environment variable (default: CLERK_SECRET_KEY)" >&2
  echo "or from a .env file in the project root." >&2
  exit 1
fi

USER_ID="$1"
SECRET_VAR="${2:-CLERK_SECRET_KEY}"
SECRET="${!SECRET_VAR:-}"

# Fallback: try loading from .env in project root
if [ -z "$SECRET" ]; then
  SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
  PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
  ENV_FILE="$PROJECT_DIR/../.env"
  if [ -f "$ENV_FILE" ]; then
    set -a
    source "$ENV_FILE" 2>/dev/null || true
    set +a
    SECRET="${!SECRET_VAR:-}"
  fi
fi

if [ -z "$SECRET" ]; then
  echo "Error: $SECRET_VAR is not set and no .env file found" >&2
  echo "" >&2
  echo "Set it inline:" >&2
  echo "  $SECRET_VAR=sk_test_xxx $(basename "$0") $USER_ID" >&2
  echo "Or add to .env in the repo root:" >&2
  echo "  $SECRET_VAR=sk_test_xxx" >&2
  exit 1
fi

generate_jwt_via_node() {
  node --input-type=module - "$1" "$2" <<'JWTSCRIPT' 2>/dev/null
import { createHmac } from 'node:crypto';

const userId = process.argv[1];
const secret = process.argv[2];
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
const now = Math.floor(Date.now() / 1000);
const payload = Buffer.from(JSON.stringify({
  sub: userId,
  iat: now,
  exp: now + 2592000
})).toString('base64url');
const sig = createHmac('sha256', secret).update(header + '.' + payload).digest('base64url');
console.log(header + '.' + payload + '.' + sig);
JWTSCRIPT
}

generate_jwt_via_openssl() {
  local now header payload sig
  now=$(date +%s)
  header=$(echo -n '{"alg":"HS256","typ":"JWT"}' | base64 | tr '+/' '-_' | tr -d '=')
  payload=$(echo -n "{\"sub\":\"$USER_ID\",\"iat\":$now,\"exp\":$((now + 2592000))}" | base64 | tr '+/' '-_' | tr -d '=')
  sig=$(echo -n "$header.$payload" | openssl dgst -sha256 -hmac "$SECRET" -binary | base64 | tr '+/' '-_' | tr -d '=')
  echo "$header.$payload.$sig"
}

if command -v node &>/dev/null; then
  generate_jwt_via_node "$USER_ID" "$SECRET"
elif command -v openssl &>/dev/null; then
  generate_jwt_via_openssl
else
  echo "Error: need either node or openssl to generate JWT" >&2
  exit 1
fi
