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

# Run the repository DDL through the live compose MySQL container. Docker's
# /docker-entrypoint-initdb.d hook only runs for an empty volume, while local
# development volumes often outlive schema additions between services.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-root}"
DEPLOY_PLATFORM_ROOT="${DEPLOY_PLATFORM_ROOT:-${PROJECT_ROOT}/../deploy-platform}"

cd "${PROJECT_ROOT}"

SQL_FILES=(
	"services/room-service/deploy/mysql/initdb/001_room_service.sql"
	"services/user-service/deploy/mysql/initdb/001_user_service.sql"
	"services/wallet-service/deploy/mysql/initdb/001_wallet_service.sql"
	"services/activity-service/deploy/mysql/initdb/001_activity_service.sql"
	"${DEPLOY_PLATFORM_ROOT}/deploy/mysql/initdb/005_utf8mb4_chinese_support.sql"
	"${DEPLOY_PLATFORM_ROOT}/deploy/mysql/initdb/006_admin_database.sql"
	"${DEPLOY_PLATFORM_ROOT}/deploy/mysql/initdb/007_resource_group_wallet_asset_items.sql"
	"services/cron-service/deploy/mysql/initdb/001_cron_service.sql"
	"services/game-service/deploy/mysql/initdb/001_game_service.sql"
	"services/robot-service/deploy/mysql/initdb/001_robot_service.sql"
	"services/notice-service/deploy/mysql/initdb/001_notice_service.sql"
	"services/statistics-service/deploy/mysql/initdb/001_statistics_service.sql"
	"${DEPLOY_PLATFORM_ROOT}/deploy/mysql/initdb/999_local_grants.sql"
)

# Keep MySQL as the only required dependency for this script. Business services
# are started after schema/grants are known to match the current repo.
"${SCRIPT_DIR}/prepare-local-mysql-initdb.sh"
"${SCRIPT_DIR}/resolve-compose-container-conflicts.sh" mysql
docker compose up -d mysql >/dev/null

# `docker compose up` may recreate MySQL after command/config changes. Wait on
# the server port before applying DDL so initdb is reliable on fresh containers.
for _ in {1..60}; do
	if docker compose exec -T mysql mysqladmin ping -h 127.0.0.1 -uroot -p"${MYSQL_ROOT_PASSWORD}" --silent >/dev/null 2>&1; then
		break
	fi

	sleep 1
done

if ! docker compose exec -T mysql mysqladmin ping -h 127.0.0.1 -uroot -p"${MYSQL_ROOT_PASSWORD}" --silent >/dev/null 2>&1; then
	printf 'mysql did not become ready before initdb\n' >&2
	exit 1
fi

for sql_file in "${SQL_FILES[@]}"; do
	if [[ ! -f "${sql_file}" ]]; then
		# Platform/admin seed files may live in a sibling deploy repository that
		# is absent on lightweight app-backend checkouts. Treat those inputs as
		# optional so local service startup can still exercise the owned schemas.
		printf 'skipping mysql init file because it is absent or not a regular file: %s\n' "${sql_file}"
		continue
	fi

	printf 'applying mysql init file: %s\n' "${sql_file}"
	docker compose exec -T mysql mysql --default-character-set=utf8mb4 -h 127.0.0.1 -uroot -p"${MYSQL_ROOT_PASSWORD}" < "${sql_file}"
done
