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

# ============================================================
# pull-prod-db.sh — Importe la BDD inventory_prod de prod en local
# ============================================================
#
# Usage : ./scripts/pull-prod-db.sh [SSH_HOST]
#
# SSH_HOST : alias ou adresse du serveur prod (default: prod)
#
# Prérequis :
#   - Accès SSH au serveur de prod
#   - Docker en cours sur la prod (conteneur "postgres", user "admin")
#   - Docker compose Inventory en cours en local (make start)

SSH_HOST="${1:-matt@prod.malio-dev.fr}"
PROD_CONTAINER="postgres"
PROD_DB="inventory_prod"
PROD_USER="admin"

LOCAL_COMPOSE="docker compose --env-file infra/dev/.env.docker"
LOCAL_DB_SERVICE="db"
LOCAL_DB="inventory"
LOCAL_USER="root"

DUMP_FILE="/tmp/inventory_prod_dump.sql"

echo "==> Dump de ${PROD_DB} depuis ${SSH_HOST}..."
ssh "${SSH_HOST}" "docker exec ${PROD_CONTAINER} pg_dump -U ${PROD_USER} -d ${PROD_DB} \
    --no-owner --no-privileges --clean --if-exists" > "${DUMP_FILE}"

DUMP_SIZE=$(du -h "${DUMP_FILE}" | cut -f1)
echo "==> Dump recu : ${DUMP_FILE} (${DUMP_SIZE})"

echo "==> Reset de la BDD locale (${LOCAL_DB})..."
${LOCAL_COMPOSE} exec -T ${LOCAL_DB_SERVICE} psql -U ${LOCAL_USER} -d postgres -c \
    "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${LOCAL_DB}' AND pid <> pg_backend_pid();" > /dev/null 2>&1 || true
${LOCAL_COMPOSE} exec -T ${LOCAL_DB_SERVICE} psql -U ${LOCAL_USER} -d postgres -c \
    "DROP DATABASE IF EXISTS ${LOCAL_DB};"
${LOCAL_COMPOSE} exec -T ${LOCAL_DB_SERVICE} psql -U ${LOCAL_USER} -d postgres -c \
    "CREATE DATABASE ${LOCAL_DB};"

echo "==> Import du dump dans la BDD locale..."
${LOCAL_COMPOSE} exec -T ${LOCAL_DB_SERVICE} psql -U ${LOCAL_USER} -d ${LOCAL_DB} < "${DUMP_FILE}"

echo "==> Nettoyage..."
rm -f "${DUMP_FILE}"

echo ""
echo "Done! BDD locale '${LOCAL_DB}' synchronisee avec '${PROD_DB}' de prod."
