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

# Local services start RocketMQ consumers before any business event is produced,
# so relying on producer-side auto topic creation makes a fresh broker fail at
# startup. Keep the fixed owner-outbox topics explicit and idempotent here.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

cd "${PROJECT_ROOT}"

"${SCRIPT_DIR}/prepare-local-rocketmq-config.sh" >/dev/null
export ROCKETMQ_BROKER_CONFIG="${PROJECT_ROOT}/tmp/rocketmq/broker.local.conf"
"${SCRIPT_DIR}/resolve-compose-container-conflicts.sh" rocketmq-namesrv rocketmq-broker
docker compose up -d rocketmq-namesrv >/dev/null
docker compose up -d --force-recreate rocketmq-broker >/dev/null

MQADMIN="/home/rocketmq/rocketmq-5.3.1/bin/mqadmin"
NAMESRV="rocketmq-namesrv:9876"
CLUSTER="hyapp-local"
TOPICS=(
	"hyapp_wallet_outbox"
	"hyapp_wallet_realtime_outbox"
	"hyapp_room_outbox"
	"hyapp_room_rocket_launch"
	"hyapp_user_outbox"
	"hyapp_message_action_outbox"
	"hyapp_game_outbox"
)

# The broker process can accept a container start before it has registered with
# NameServer. Wait for the cluster view so updateTopic targets the real broker.
for _ in {1..60}; do
	if docker compose exec -T rocketmq-broker "${MQADMIN}" clusterList -n "${NAMESRV}" 2>/dev/null | grep -q "${CLUSTER}"; then
		break
	fi

	sleep 1
done

if ! docker compose exec -T rocketmq-broker "${MQADMIN}" clusterList -n "${NAMESRV}" 2>/dev/null | grep -q "${CLUSTER}"; then
	printf 'rocketmq broker did not register in cluster %s before topic init\n' "${CLUSTER}" >&2
	exit 1
fi

for topic in "${TOPICS[@]}"; do
	printf 'applying rocketmq topic: %s\n' "${topic}"
	docker compose exec -T rocketmq-broker "${MQADMIN}" updateTopic -n "${NAMESRV}" -c "${CLUSTER}" -t "${topic}" -r 8 -w 8 >/dev/null
done
