#!/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}"
LOCAL_INITDB_DIR="${PROJECT_ROOT}/tmp/mysql/initdb"

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"
	"${LOCAL_INITDB_DIR}/005_utf8mb4_chinese_support.sql"
	"${LOCAL_INITDB_DIR}/006_admin_database.sql"
	"${LOCAL_INITDB_DIR}/007_resource_group_wallet_asset_items.sql"
	"services/lucky-gift-service/deploy/mysql/initdb/001_lucky_gift_service.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"
	"${LOCAL_INITDB_DIR}/999_local_grants.sql"
)

# initdb only creates missing tables; a reused local MySQL volume therefore
# needs incremental migrations as well. Keep owner migrations here when reused
# volumes need more than CREATE TABLE IF NOT EXISTS can provide; otherwise new
# binaries may start against a structurally valid-looking but stale table.
INCREMENTAL_MIGRATION_FILES=(
	"services/user-service/deploy/mysql/migrations/012_login_audit_client_version.sql"
	"services/user-service/deploy/mysql/migrations/017_cp_application_gift_coin_value.sql"
	"services/user-service/deploy/mysql/migrations/018_auth_refresh_token_rotation.sql"
	"services/user-service/deploy/mysql/migrations/019_user_profile_anonymous_visits.sql"
	"services/user-service/deploy/mysql/migrations/020_user_avatar_upload_registrations.sql"
	"services/room-service/deploy/mysql/migrations/003_room_vip_media_and_decorations.sql"
	"services/room-service/deploy/mysql/migrations/004_room_list_owner_vip_level.sql"
	"services/room-service/deploy/mysql/migrations/005_room_list_activity_indicators.sql"
	"services/room-service/deploy/mysql/migrations/006_room_list_owner_vip_fallback.sql"
	"services/activity-service/deploy/mysql/migrations/013_game_win_broadcast_config.sql"
	"services/wallet-service/deploy/mysql/migrations/002_resource_shop_price_tiers.sql"
	"services/wallet-service/deploy/mysql/migrations/003_vip_resource_equipment_contract.sql"
	"services/wallet-service/deploy/mysql/migrations/010_fami_agency_host_income_share.sql"
	"services/wallet-service/deploy/mysql/migrations/011_vip_user_settings_defaults.sql"
	"services/wallet-service/deploy/mysql/migrations/012_wallet_outbox_archive_receipts.sql"
	"services/wallet-service/deploy/mysql/migrations/013_wallet_outbox_archive_purge_receipts.sql"
	"services/wallet-service/deploy/mysql/migrations/018_host_salary_policy_revisions.sql"
	"services/lucky-gift-service/deploy/mysql/migrations/013_jackpot_token_version_rate_limit.sql"
	"services/statistics-service/deploy/mysql/migrations/003_social_profile_setup_view.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

for sql_file in "${INCREMENTAL_MIGRATION_FILES[@]}"; do
	if [[ ! -f "${sql_file}" ]]; then
		printf 'skipping mysql migration because it is absent or not a regular file: %s\n' "${sql_file}"
		continue
	fi

	printf 'applying mysql migration: %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
