#!/bin/bash
# ============================================================================
# ERP GENERIC - DROP DATABASE SCRIPT
# ============================================================================
# Description: Drops the ERP Generic database
# Usage: ./scripts/drop-database.sh [--force]
# ============================================================================

set -e

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

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DATABASE_DIR="$(dirname "$SCRIPT_DIR")"

# Load environment variables
if [ -f "$DATABASE_DIR/.env" ]; then
    source "$DATABASE_DIR/.env"
elif [ -f "$DATABASE_DIR/.env.example" ]; then
    source "$DATABASE_DIR/.env.example"
fi

# Default values
POSTGRES_HOST="${POSTGRES_HOST:-localhost}"
POSTGRES_PORT="${POSTGRES_PORT:-5432}"
POSTGRES_DB="${POSTGRES_DB:-erp_generic}"
POSTGRES_USER="${POSTGRES_USER:-erp_admin}"
POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-erp_secret_2024}"

# Connection string
export PGPASSWORD="$POSTGRES_PASSWORD"
PSQL_CMD="psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U $POSTGRES_USER"

# Check for --force flag
FORCE=false
if [ "$1" == "--force" ]; then
    FORCE=true
fi

echo -e "${RED}============================================${NC}"
echo -e "${RED}   ERP GENERIC - DROP DATABASE${NC}"
echo -e "${RED}============================================${NC}"
echo ""
echo -e "Database: ${YELLOW}$POSTGRES_DB${NC}"
echo ""

if [ "$FORCE" != true ]; then
    echo -e "${RED}WARNING: This will permanently delete all data!${NC}"
    read -p "Are you sure you want to drop the database? (y/N): " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo "Aborted."
        exit 0
    fi
fi

echo -e "${BLUE}Terminating active connections...${NC}"
$PSQL_CMD -d postgres -c "
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = '$POSTGRES_DB'
  AND pid <> pg_backend_pid();
" 2>/dev/null || true

echo -e "${BLUE}Dropping database...${NC}"
$PSQL_CMD -d postgres -c "DROP DATABASE IF EXISTS $POSTGRES_DB;"

echo ""
echo -e "${GREEN}Database '$POSTGRES_DB' has been dropped.${NC}"
echo ""
