#!/usr/bin/env bash
# ============================================================================
# ChatApp - PostgreSQL Restore Script
# Restores a compressed backup of the chatapp database
# Usage: ./scripts/restore-postgres.sh <backup_file>
# ============================================================================
set -euo pipefail

# Configuration
CONTAINER_NAME="${POSTGRES_CONTAINER:-chatapp-postgres}"
DB_USER="${POSTGRES_USER:-chatapp}"
DB_NAME="${POSTGRES_DB:-chatapp}"

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

echo -e "${YELLOW}=== ChatApp PostgreSQL Restore ===${NC}"

# Validate arguments
if [ $# -lt 1 ]; then
  echo -e "${RED}Usage: $0 <backup_file>${NC}"
  echo -e "Example: $0 ./backups/chatapp_20260714_120000.sql.gz"
  exit 1
fi

BACKUP_FILE="$1"

if [ ! -f "${BACKUP_FILE}" ]; then
  echo -e "${RED}Error: Backup file '${BACKUP_FILE}' not found${NC}"
  exit 1
fi

echo -e "Container: ${CONTAINER_NAME}"
echo -e "Database:  ${DB_NAME}"
echo -e "Backup:    ${BACKUP_FILE}"
echo ""

# Check if container is running
if ! docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
  echo -e "${RED}Error: Container '${CONTAINER_NAME}' is not running${NC}"
  exit 1
fi

# Confirm
echo -e "${RED}WARNING: This will DROP and recreate the database '${DB_NAME}'!${NC}"
read -p "Are you sure you want to continue? (yes/no): " CONFIRM
if [ "${CONFIRM}" != "yes" ]; then
  echo -e "${YELLOW}Restore cancelled${NC}"
  exit 0
fi

echo ""
echo -e "${YELLOW}Dropping existing database...${NC}"
docker exec "${CONTAINER_NAME}" \
  psql -U "${DB_USER}" -d postgres -c "DROP DATABASE IF EXISTS ${DB_NAME};" 2>/dev/null || true

echo -e "${YELLOW}Creating fresh database...${NC}"
docker exec "${CONTAINER_NAME}" \
  psql -U "${DB_USER}" -d postgres -c "CREATE DATABASE ${DB_NAME};" 2>/dev/null || true

echo -e "${YELLOW}Restoring backup...${NC}"
gunzip -c "${BACKUP_FILE}" | docker exec -i "${CONTAINER_NAME}" \
  psql -U "${DB_USER}" -d "${DB_NAME}" 2>&1 | grep -v "^$" || true

echo -e "${GREEN}=== Restore Complete ===${NC}"
echo -e "Database '${DB_NAME}' restored from '${BACKUP_FILE}'"