#!/usr/bin/env bash
set -euo pipefail

# Production smoke test only. It intentionally does not create an application,
# because a real application always notifies the manager group.

bot_token="$(tr -d '\r\n' < /home/openclaw/.openclaw/credentials/telegram/thaifortravel-bot.token)"
test_user_id="${E2E_TELEGRAM_USER_ID:-}"
test_username="${E2E_TELEGRAM_USERNAME:-max958166}"

if ! [[ "${test_user_id}" =~ ^[1-9][0-9]*$ ]]; then
  printf '%s\n' "E2E_TELEGRAM_USER_ID must be the positive ID of a private Telegram user" >&2
  exit 2
fi

init_data="$(
  BOT_TOKEN="${bot_token}" TEST_USER_ID="${test_user_id}" TEST_USERNAME="${test_username}" node -e '
    const crypto = require("node:crypto");
    const user = JSON.stringify({
      id: Number(process.env.TEST_USER_ID),
      first_name: "Maksim",
      username: process.env.TEST_USERNAME,
      language_code: "ru",
      allows_write_to_pm: true
    });
    const fields = {
      auth_date: String(Math.floor(Date.now() / 1000)),
      query_id: `TFT-SMOKE-${Date.now()}`,
      user
    };
    const dataCheckString = Object.entries(fields)
      .sort(([left], [right]) => left.localeCompare(right))
      .map(([key, value]) => `${key}=${value}`)
      .join("\n");
    const secret = crypto
      .createHmac("sha256", "WebAppData")
      .update(process.env.BOT_TOKEN)
      .digest();
    const hash = crypto
      .createHmac("sha256", secret)
      .update(dataCheckString)
      .digest("hex");
    process.stdout.write(new URLSearchParams({ ...fields, hash }).toString());
  '
)"

profile="$(
  curl -fsS 'https://api.thaifortravel.ru/v1/me' \
    -H "Authorization: tma ${init_data}"
)"
catalog="$(
  curl -fsS 'https://api.thaifortravel.ru/v1/catalog/tours?page=1&per_page=1'
)"

jq -n \
  --argjson profile "${profile}" \
  --argjson catalog "${catalog}" \
  '{
    authenticatedUser: {
      telegramUserId: $profile.telegramUserId,
      username: $profile.username
    },
    catalog: {
      firstTourId: $catalog.data[0].id,
      firstTourTitle: $catalog.data[0].title
    },
    messagesSent: 0,
    applicationsCreated: 0
  }'

unset bot_token test_user_id test_username init_data
