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

APP_CODE="${APP_CODE:-lalu}"
STAT_TZ="${STAT_TZ:-Asia/Shanghai}"
START_DAY="${START_DAY:-$(TZ=Asia/Shanghai date +%F)}"
END_DAY="${END_DAY:-$START_DAY}"

STATISTICS_MYSQL_DSN="${STATISTICS_MYSQL_DSN:-hyapp:hyapp@tcp(127.0.0.1:23306)/hyapp_statistics?parseTime=true&charset=utf8mb4&loc=UTC&multiStatements=true}"
USER_MYSQL_DSN="${USER_MYSQL_DSN:-hyapp:hyapp@tcp(127.0.0.1:23306)/hyapp_user?parseTime=true&charset=utf8mb4&loc=UTC&multiStatements=true}"
WALLET_MYSQL_DSN="${WALLET_MYSQL_DSN:-hyapp:hyapp@tcp(127.0.0.1:23306)/hyapp_wallet?parseTime=true&charset=utf8mb4&loc=UTC&multiStatements=true}"
ROOM_MYSQL_DSN="${ROOM_MYSQL_DSN:-hyapp:hyapp@tcp(127.0.0.1:23306)/hyapp_room?parseTime=true&charset=utf8mb4&loc=UTC&multiStatements=true}"
GAME_MYSQL_DSN="${GAME_MYSQL_DSN:-hyapp:hyapp@tcp(127.0.0.1:23306)/hyapp_game?parseTime=true&charset=utf8mb4&loc=UTC&multiStatements=true}"

export APP_CODE STAT_TZ START_DAY END_DAY
export STATISTICS_MYSQL_DSN USER_MYSQL_DSN WALLET_MYSQL_DSN ROOM_MYSQL_DSN GAME_MYSQL_DSN

echo "Databi real-flow check"
echo "  app=${APP_CODE}"
echo "  stat_tz=${STAT_TZ}"
echo "  days=${START_DAY}..${END_DAY}"
echo
echo "Before running this check, exercise the real local business flows for the selected days."
echo "Recharge is the only metric that may use a local simulated recharge/payment callback."
echo

go run ./services/statistics-service/cmd/replay-stat-tz \
  -app "${APP_CODE}" \
  -timezone "${STAT_TZ}" \
  -start-day "${START_DAY}" \
  -end-day "${END_DAY}" \
  -apply \
  -statistics-dsn "${STATISTICS_MYSQL_DSN}" \
  -user-dsn "${USER_MYSQL_DSN}" \
  -wallet-dsn "${WALLET_MYSQL_DSN}" \
  -room-dsn "${ROOM_MYSQL_DSN}" \
  -game-dsn "${GAME_MYSQL_DSN}"

go run ./services/statistics-service/cmd/databi-real-flow-audit \
  -app "${APP_CODE}" \
  -timezone "${STAT_TZ}" \
  -start-day "${START_DAY}" \
  -end-day "${END_DAY}" \
  -statistics-dsn "${STATISTICS_MYSQL_DSN}" \
  -user-dsn "${USER_MYSQL_DSN}" \
  -wallet-dsn "${WALLET_MYSQL_DSN}" \
  -room-dsn "${ROOM_MYSQL_DSN}" \
  -game-dsn "${GAME_MYSQL_DSN}"

echo
echo "Databi real-flow check passed."
