#!/usr/bin/env bash
# Hands-On tutorial — apply the canonical MIB migrations to handson_mib.
#
# Single-database setup: ALL seven canonical assemblies go into the same
# database. (Earlier drafts tried to split UI rows into a separate
# handson_cms database, but the FrontEnd migrations seed rows into
# MEDIA_TYPES — which requires the meta-model migrations on the same
# database — so the two-DB pattern fails at boot.)
#
# Run AFTER `docker compose up -d sqlserver` + `bootstrap-databases.sh`,
# and BEFORE bringing up auth/api/permission/frontend.
#
# Usage:
#   MIB_MIGRATOR_DIR=/path/to/MibMigrator ./run-canonical-migrations.sh
#
# Assumes MibMigrator is built in Release.

set -euo pipefail

MIB_MIGRATOR_DIR="${MIB_MIGRATOR_DIR:?Set MIB_MIGRATOR_DIR to your local MibMigrator checkout}"
BIN="${MIB_MIGRATOR_DIR}/MediaiBox.Tools.Migrator/bin/Release/net8.0"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CFG="${SCRIPT_DIR}/handson-mib"

if [ ! -f "${BIN}/mibmigrator.dll" ]; then
  echo "[!] Release binaries not found at ${BIN}/mibmigrator.dll" >&2
  echo "    Build MibMigrator first:  cd ${MIB_MIGRATOR_DIR} && dotnet build -c Release" >&2
  exit 1
fi

run_migrator() {
  local label="$1"; shift
  echo
  echo ">>> ${label}"
  dotnet "${BIN}/mibmigrator.dll" \
    "$@" \
    -configPath="${CFG}" \
    -section=default \
    -logInformation=minimal \
    | grep -E "Migration done|ERROR|Status: \"" \
    | tail -3 || true
}

echo "=== Migrating handson_mib (single database for everything) ==="

run_migrator "Core (framework foundations)" \
  -assembly="${BIN}/MediaiBox.Core.Database.Migrations.dll" -target=HEAD

run_migrator "CMS API (MEDIA_TYPES / ADM_FIELDS / ADM_RELATEDS)" \
  -assembly="${BIN}/MediaiBox.Cms.Api.Database.Migrations.dll" -target=HEAD

run_migrator "CMS DataModel (instances, sources, generic seed)" \
  -assembly="${BIN}/MediaiBox.Cms.DataModel.Database.Migrations.dll" -target=HEAD

run_migrator "ContentCriteria (CONTENT_CRITERIA_* tables)" \
  -assembly="${BIN}/MediaiBox.ContentCriteria.Database.Migrations.dll" -target=HEAD

run_migrator "Authorization (AUTH_* — OAuth2 clients, scopes, tokens)" \
  -assembly="${BIN}/MediaiBox.Cms.Authorization.Database.Migrations.dll" -target=HEAD

run_migrator "CMS FrontEnd UI (MIB3UX_* + default component rows)" \
  -assembly="${BIN}/MediaiBox.Cms.FrontEnd.Database.Migrations.dll" -target=HEAD

run_migrator "Default Pages (built-in admin UI pages)" \
  -assembly="${BIN}/MediaiBox.Cms.DefaultPages.Database.Migrations.dll" -target=HEAD

echo
echo "✓ Canonical migrations applied successfully."
