#!/usr/bin/env bash
# Mongo migration（golang-migrate；不建立預設帳號）
set -euo pipefail
# shellcheck source=_common.sh
source "$(cd "$(dirname "$0")" && pwd)/_common.sh"

load_env
require_cmd go

ensure_migrate() {
  if command -v migrate >/dev/null 2>&1; then
    return
  fi
  log "installing golang-migrate (mongodb tag)…"
  go install -tags 'mongodb' github.com/golang-migrate/migrate/v4/cmd/migrate@v4.18.3
  export PATH="${PATH}:$(go env GOPATH)/bin"
  command -v migrate >/dev/null 2>&1 || die "migrate 安裝失敗，請確認 GOPATH/bin 在 PATH"
}

ensure_migrate
export PATH="${PATH}:$(go env GOPATH)/bin"

# 組 MONGO_URL
if [[ -z "${MONGO_URL:-}" ]]; then
  die "MONGO_URL 未設定"
fi

# Never print MONGO_URL because it commonly contains database credentials.
log "migrate up → configured MongoDB"
cd "$BACKEND_DIR"
migrate -path generate/database/mongo -database "$MONGO_URL" up
migrate -path generate/database/mongo -database "$MONGO_URL" version || true

log "migration 不建立預設管理員；首次部署請以 runtime secret 執行 seeder"
log "migrate done"
