#!/usr/bin/env bash
# Apply pending migrations.
#
# The backend auto-applies embedded migrations at boot (AUTO_MIGRATE=true,
# the default). This script exists for explicit/CI/manual runs using Atlas.
#
# Usage: ./scripts/migrate.sh   (DATABASE_URL from .env or environment)
set -euo pipefail
cd "$(dirname "$0")/.."
if [ -f .env ]; then set -a; source .env; set +a; fi
: "${DATABASE_URL:?DATABASE_URL is required}"

if command -v atlas >/dev/null 2>&1; then
  atlas migrate apply --dir file://migrations --url "$DATABASE_URL"
elif [ -f .env ] && grep -q POSTGRES_USER .env && command -v docker >/dev/null 2>&1; then
  docker run --rm --network host arigaio/atlas:latest \
    migrate apply --dir file:///migrations --url "$DATABASE_URL"
else
  echo "atlas CLI not found. Install it (https://atlasgo.io) or rely on the" >&2
  echo "backend's automatic boot migration (AUTO_MIGRATE=true, default)." >&2
  exit 1
fi
echo "Migrations applied."
