#!/usr/bin/env bash
# Builds a self-contained EF Core migration bundle for VigilCareClinicalAPI.
# CD (Phase 36 Step 12) runs the same command; this script is for local dry-runs
# and for operators who apply schema changes before rolling the API image.
#
# Usage (from repo root or anywhere):
#   ./scripts/build-api-migration-bundle.sh
#   RID=win-x64 ./scripts/build-api-migration-bundle.sh   # local Windows test
#
# Apply against a database (DDL-privileged connection string):
#   ./artifacts/migrate-api --connection "$PG_CONNECTION_DDL"
#
# Zero-downtime discipline: every migration must be backwards-compatible with
# the previously deployed API image (expand-then-contract). The bundle runs
# while old containers are still serving traffic.
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT_DIR="${OUT_DIR:-${ROOT_DIR}/artifacts}"
RID="${RID:-linux-x64}"
OUTPUT="${OUT_DIR}/migrate-api"

# Git Bash on Windows often lacks the host PATH; prefer known install locations.
if ! command -v dotnet >/dev/null 2>&1; then
  for candidate in \
    "/c/Program Files/dotnet/dotnet" \
    "/mnt/c/Program Files/dotnet/dotnet" \
    "${HOME}/.dotnet/dotnet"
  do
    if [[ -x "${candidate}" ]]; then
      PATH="$(dirname "${candidate}"):${PATH}"
      export PATH
      break
    fi
  done
fi

if ! command -v dotnet >/dev/null 2>&1; then
  echo "dotnet SDK is required (not found on PATH)." >&2
  exit 1
fi

mkdir -p "${OUT_DIR}"

# Prefer a globally installed dotnet-ef; install 8.0.4 when nothing is present.
# A newer global tool is fine — do not downgrade an existing install.
if ! dotnet ef --version >/dev/null 2>&1; then
  echo "Installing dotnet-ef 8.0.4..."
  dotnet tool install --global dotnet-ef --version 8.0.4
  export PATH="${PATH}:${HOME}/.dotnet/tools:${USERPROFILE:-}/.dotnet/tools"
fi

echo "Building API migration bundle → ${OUTPUT} (RID=${RID})"
dotnet ef migrations bundle \
  --project "${ROOT_DIR}/VigilCareClinicalAPI" \
  --startup-project "${ROOT_DIR}/VigilCareClinicalAPI" \
  --configuration Release \
  --self-contained -r "${RID}" \
  --output "${OUTPUT}" \
  --force

echo "Bundle ready: ${OUTPUT}"
echo "Apply with: ${OUTPUT} --connection \"\$PG_CONNECTION_DDL\""
