#!/bin/bash
# BreakPilot Database Restore Script
# Stellt ein Backup der PostgreSQL-Datenbank wieder her

set -e

# Konfiguration
BACKUP_DIR="${BACKUP_DIR:-./backups}"
CONTAINER_NAME="${CONTAINER_NAME:-breakpilot-pwa-postgres}"
DB_USER="${DB_USER:-breakpilot}"
DB_NAME="${DB_NAME:-breakpilot_db}"

# Farben für Output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== BreakPilot Database Restore ===${NC}"
echo ""

# Backup-Datei als Argument oder automatisch das neueste wählen
if [ -n "$1" ]; then
    BACKUP_FILE="$1"
else
    # Neuestes Backup finden
    BACKUP_FILE=$(ls -t "$BACKUP_DIR"/breakpilot_*.sql.gz 2>/dev/null | head -1)

    if [ -z "$BACKUP_FILE" ]; then
        echo -e "${RED}Error: No backup files found in $BACKUP_DIR${NC}"
        exit 1
    fi

    echo -e "${YELLOW}No backup file specified. Using most recent:${NC}"
    echo "$BACKUP_FILE"
    echo ""
fi

# Prüfen ob Backup-Datei existiert
if [ ! -f "$BACKUP_FILE" ]; then
    echo -e "${RED}Error: Backup file not found: $BACKUP_FILE${NC}"
    exit 1
fi

# Prüfen ob Container läuft
if ! docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${RED}Error: Container '$CONTAINER_NAME' is not running${NC}"
    exit 1
fi

# Warnung anzeigen
echo -e "${RED}⚠️  WARNING: This will overwrite all current data!${NC}"
echo ""
read -p "Are you sure you want to restore from this backup? (yes/no): " CONFIRM

if [ "$CONFIRM" != "yes" ]; then
    echo "Restore cancelled."
    exit 0
fi

echo ""
echo -e "${YELLOW}Stopping dependent services...${NC}"

# Consent Service stoppen (falls läuft)
docker stop breakpilot-pwa-consent-service 2>/dev/null || true
docker stop breakpilot-pwa-backend 2>/dev/null || true

echo -e "${YELLOW}Restoring database...${NC}"

# Datenbank droppen und neu erstellen
docker exec "$CONTAINER_NAME" psql -U "$DB_USER" -d postgres -c "DROP DATABASE IF EXISTS ${DB_NAME};"
docker exec "$CONTAINER_NAME" psql -U "$DB_USER" -d postgres -c "CREATE DATABASE ${DB_NAME};"

# Backup wiederherstellen
gunzip -c "$BACKUP_FILE" | docker exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME"

echo -e "${GREEN}✓ Database restored successfully${NC}"

echo ""
echo -e "${YELLOW}Restarting services...${NC}"

# Services wieder starten
docker start breakpilot-pwa-consent-service 2>/dev/null || true
docker start breakpilot-pwa-backend 2>/dev/null || true

# Warten bis Services bereit sind
sleep 5

echo ""
echo -e "${GREEN}=== Restore completed! ===${NC}"
echo ""
echo "Verify the restore by checking:"
echo "  - http://localhost:8000/app"
echo "  - http://localhost:8081/health"
