#!/bin/bash
set -euo pipefail

if [ $# -lt 1 ]; then
  echo "Usage: $0 /absolute/path/to/zgz_turismo.sql"
  exit 1
fi

SQL_FILE="$1"
POSTGRES_CONTAINER="${POSTGRES_CONTAINER:-zgz_postgres}"
DIRECTUS_CONTAINER="${DIRECTUS_CONTAINER:-zgz_directus}"
DB_NAME="${DB_NAME:-zgz_turismo}"
DB_USER="${DB_USER:-directus}"

if [ ! -f "$SQL_FILE" ]; then
  echo "SQL file not found: $SQL_FILE"
  exit 1
fi

if ! command -v docker >/dev/null 2>&1; then
  echo "docker is not installed or not in PATH"
  exit 1
fi

if ! docker ps --format '{{.Names}}' | grep -Fxq "$POSTGRES_CONTAINER"; then
  echo "Postgres container '$POSTGRES_CONTAINER' is not running."
  exit 1
fi

echo "Stopping Directus container '$DIRECTUS_CONTAINER'..."
docker stop "$DIRECTUS_CONTAINER" >/dev/null 2>&1 || true

echo "Resetting public schema in database '$DB_NAME'..."
docker exec -i "$POSTGRES_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"

echo "Importing dump from '$SQL_FILE'..."
cat "$SQL_FILE" | docker exec -i "$POSTGRES_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME"

echo "Starting Directus container '$DIRECTUS_CONTAINER'..."
docker start "$DIRECTUS_CONTAINER" >/dev/null

echo "Restore complete. Run scripts/verify_restore.sh on the server next."
