#!/usr/bin/env bash
# One-time helper: obtain a Gmail API refresh token for MAIL_TRANSPORT=gmail_api
#
# Prerequisites:
#   1. Google Cloud project with Gmail API enabled
#   2. OAuth client (same GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET as calendar)
#   3. Add redirect URI: http://localhost:53682/oauth2callback
#
# Usage (from repo root or node/):
#   bash scripts/get-gmail-refresh-token.sh
#
# Then set in node/.env:
#   MAIL_TRANSPORT=gmail_api
#   GMAIL_REFRESH_TOKEN=<printed token>
#   GMAIL_USER=your-sending-mailbox@gmail.com
#   EMAIL_FROM=your-sending-mailbox@gmail.com
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="$ROOT/node/.env"
# shellcheck disable=SC1090
source "$ENV_FILE"

CLIENT_ID="${GOOGLE_CLIENT_ID:-}"
CLIENT_SECRET="${GOOGLE_CLIENT_SECRET:-}"
REDIRECT="http://localhost:53682/oauth2callback"
SCOPE="https://www.googleapis.com/auth/gmail.send%20https://www.googleapis.com/auth/userinfo.email"

if [[ -z "$CLIENT_ID" || -z "$CLIENT_SECRET" ]]; then
  echo "Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in node/.env first." >&2
  exit 1
fi

AUTH_URL="https://accounts.google.com/o/oauth2/v2/auth?client_id=${CLIENT_ID}&redirect_uri=$(python3 -c "import urllib.parse; print(urllib.parse.quote('${REDIRECT}', safe=''))")&response_type=code&scope=${SCOPE}&access_type=offline&prompt=consent"

echo "1) Open this URL in a browser and sign in as the mailbox that will SEND mail:"
echo ""
echo "$AUTH_URL"
echo ""
echo "2) After consent, you will land on a localhost URL that fails to load — copy the full URL"
echo "   (or just the ?code=... value) and paste it below."
echo ""
read -r -p "Paste redirect URL or code: " INPUT

CODE="$INPUT"
if [[ "$INPUT" == *code=* ]]; then
  CODE="$(python3 -c "import urllib.parse,sys; u=urllib.parse.urlparse(sys.argv[1]); print(urllib.parse.parse_qs(u.query).get('code',[''])[0])" "$INPUT")"
fi

if [[ -z "$CODE" ]]; then
  echo "No authorization code found." >&2
  exit 1
fi

RESP="$(curl -sS -X POST https://oauth2.googleapis.com/token \
  -d "code=${CODE}" \
  -d "client_id=${CLIENT_ID}" \
  -d "client_secret=${CLIENT_SECRET}" \
  -d "redirect_uri=${REDIRECT}" \
  -d "grant_type=authorization_code")"

REFRESH="$(python3 -c "import json,sys; print(json.load(sys.stdin).get('refresh_token') or '')" <<<"$RESP")"
if [[ -z "$REFRESH" ]]; then
  echo "Failed to get refresh_token. Response:" >&2
  echo "$RESP" >&2
  exit 1
fi

echo ""
echo "Add these to node/.env:"
echo "MAIL_TRANSPORT=gmail_api"
echo "GMAIL_REFRESH_TOKEN=${REFRESH}"
echo "GMAIL_USER=<the Gmail address you signed in with>"
echo ""
echo "Also add redirect URI in Google Cloud Console:"
echo "  ${REDIRECT}"
