#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR="${1:-}"
POSTGRES_CONTAINER="${POSTGRES_CONTAINER:-xiaoxia-postgres}"
POSTGRES_USER="${POSTGRES_USER:-xiaoxia}"
POSTGRES_DB="${POSTGRES_DB:-xiaoxia_saas}"

if [ -z "$BACKUP_DIR" ]; then
  echo "Usage: $0 <backup-dir>" >&2
  exit 2
fi

DUMP_PATH="$BACKUP_DIR/${POSTGRES_DB}.dump"
MANIFEST_PATH="$BACKUP_DIR/manifest.txt"

if [ ! -s "$DUMP_PATH" ]; then
  echo "ERROR: backup dump not found or empty: $DUMP_PATH" >&2
  exit 1
fi

cat <<EOF
Restore plan for $POSTGRES_DB

Backup directory:
  $BACKUP_DIR

Manifest:
$(cat "$MANIFEST_PATH" 2>/dev/null || echo '  <missing manifest>')

Manual restore commands (requires maintenance window):

  docker stop xiaoxia-api-production xiaoxia-worker-production || true
  docker exec $POSTGRES_CONTAINER pg_restore -U $POSTGRES_USER -d $POSTGRES_DB --clean --if-exists --no-owner --no-privileges < $DUMP_PATH
  docker start xiaoxia-api-production xiaoxia-worker-production
  docker exec $POSTGRES_CONTAINER psql -U $POSTGRES_USER -d $POSTGRES_DB -Atc 'select version_num from alembic_version;'

This script intentionally does not execute restore automatically.
EOF
