#!/usr/bin/env sh
set -eu

BASE_URL="${BMG_CHAT_URL:-https://chat.bmgfvn.net}"
: "${BMG_CHAT_TOKEN:?Set BMG_CHAT_TOKEN to a token created in BMG Chat > Account}"

command_name="${1:-channels}"
channel="${2:-van-hanh}"

case "$command_name" in
  channels)
    curl -fsS "$BASE_URL/api/v1/channels" -H "Authorization: Bearer $BMG_CHAT_TOKEN"
    ;;
  read)
    curl -fsS "$BASE_URL/api/v1/channels/$channel/messages?limit=50" -H "Authorization: Bearer $BMG_CHAT_TOKEN"
    ;;
  send)
    text="${3:-}"
    [ -n "$text" ] || { echo "Usage: bmg-chat.sh send <channel> <text>" >&2; exit 2; }
    escaped=$(printf '%s' "$text" | sed 's/\\/\\\\/g; s/"/\\"/g')
    curl -fsS "$BASE_URL/api/v1/channels/$channel/messages" \
      -H "Authorization: Bearer $BMG_CHAT_TOKEN" \
      -H "Content-Type: application/json" \
      --data "{\"text\":\"$escaped\"}"
    ;;
  *) echo "Commands: channels | read <channel> | send <channel> <text>" >&2; exit 2 ;;
esac
