#!/bin/bash
# =============================================================================
# Aurora Database Backup Script
# =============================================================================

set -e

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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
BACKUP_DIR="$PROJECT_DIR/shared/db/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/backup_$TIMESTAMP.sql"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${YELLOW}💾 Starting database backup...${NC}"

mkdir -p "$BACKUP_DIR"

if docker ps | grep -q aurora_db; then
  # Try to dump the database
  if docker exec aurora_db pg_dump -U "${DB_USER:-auroradev}" "${DB_NAME:-auroradev}" > "$BACKUP_FILE"; then
     # Check if backup file is not empty
     if [ -s "$BACKUP_FILE" ]; then
       echo -e "  ${GREEN}✓${NC} Backup successful!"
       echo -e "  📂 File: $BACKUP_FILE"
       echo -e "  📏 Size: $(du -h "$BACKUP_FILE" | cut -f1)"
       
       # Keep only last 10 backups
       cd "$BACKUP_DIR"
       ls -t backup_*.sql | tail -n +11 | xargs -r rm --
     else
       echo -e "  ${RED}✗${NC} Backup created but empty. Something went wrong."
       rm -f "$BACKUP_FILE"
       exit 1
     fi
  else
     echo -e "  ${RED}✗${NC} pg_dump failed."
     rm -f "$BACKUP_FILE"
     exit 1
  fi
else
  echo -e "  ${RED}✗${NC} Database container (aurora_db) is not running!"
  exit 1
fi
