#!/usr/bin/env bash
# ────────────────────────────────────────────────────────────────────────────
# Payload CMS Database Backup
# Creates a timestamped pg_dump of the Payload Postgres database.
# Usage: npm run backup:db
# ────────────────────────────────────────────────────────────────────────────
set -euo pipefail

# Load environment variables
if [ -f .env ]; then
  set -a; source .env; set +a
fi

DB_NAME="${PAYLOAD_DB_NAME:-payload}"
DB_USER="${PAYLOAD_DB_USER:-payload}"
BACKUP_DIR="./backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/payload_${TIMESTAMP}.sql.gz"

# Ensure backup directory exists
mkdir -p "$BACKUP_DIR"

# Check if database container is running
if ! docker compose ps --services --filter "status=running" | grep -qx "klz-db"; then
  echo "⚠️ Database container 'klz-db' is not running. Starting it..."
  docker compose up -d klz-db
  echo "⏳ Waiting for database to be ready..."
  sleep 3
fi

echo "📦 Backing up Payload database..."
echo "   Service:   klz-db"
echo "   Database:  $DB_NAME"
echo "   Output:    $BACKUP_FILE"

# Run pg_dump inside the container and compress
docker compose exec -T klz-db pg_dump -U "$DB_USER" -d "$DB_NAME" --clean --if-exists | gzip > "$BACKUP_FILE"

# Show result
SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
echo ""
echo "✅ Backup complete: $BACKUP_FILE ($SIZE)"
echo ""

# Show existing backups
echo "📋 Available backups:"
ls -lh "$BACKUP_DIR"/*.sql.gz 2>/dev/null | awk '{print "   " $NF " (" $5 ")"}'
