#!/bin/bash

# Script to apply database migrations for Pulse application

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

echo -e "${GREEN}=== Pulse Database Migration Tool ===${NC}"
echo ""

# Check if we're using Docker
if docker ps | grep -q pulse-postgres; then
    echo -e "${YELLOW}Using Docker PostgreSQL container${NC}"
    DOCKER_MODE=true
    DB_USER="${POSTGRES_USER:-pulse_user}"
    DB_NAME="${POSTGRES_DB:-pulse_autotask}"
else
    echo -e "${YELLOW}Running in local environment${NC}"
    DOCKER_MODE=false
    # Check if psql is available
    if ! command -v psql &> /dev/null; then
        echo -e "${RED}Error: psql command not found${NC}"
        echo -e "${YELLOW}Hint: If using Docker, make sure pulse-postgres container is running${NC}"
        exit 1
    fi
    DB_CONNECTION="psql -h ${POSTGRES_HOST:-localhost} -p ${POSTGRES_PORT:-5432} -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-pulse}"
fi

# Get the migrations directory
MIGRATIONS_DIR="/opt/stacks/pulse/migrations"

# Check if migrations directory exists
if [ ! -d "$MIGRATIONS_DIR" ]; then
    echo -e "${RED}Error: Migrations directory not found at $MIGRATIONS_DIR${NC}"
    exit 1
fi

# List available migrations
echo -e "${GREEN}Available migrations:${NC}"
ls -la $MIGRATIONS_DIR/*.sql | awk '{print $9}' | xargs -I {} basename {}

echo ""

# Check if a specific migration was requested
if [ ! -z "$1" ]; then
    MIGRATION_FILE="$MIGRATIONS_DIR/$1"
    if [ ! -f "$MIGRATION_FILE" ]; then
        echo -e "${RED}Error: Migration file $1 not found${NC}"
        exit 1
    fi
    
    echo -e "${YELLOW}Applying single migration: $1${NC}"
    
    if [ "$DOCKER_MODE" = true ]; then
        docker exec -i pulse-postgres psql -U "$DB_USER" -d "$DB_NAME" < "$MIGRATION_FILE"
    else
        $DB_CONNECTION -f "$MIGRATION_FILE"
    fi
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Migration $1 applied successfully${NC}"
    else
        echo -e "${RED}✗ Failed to apply migration $1${NC}"
        exit 1
    fi
else
    # Apply all migrations in order
    echo -e "${YELLOW}Apply all migrations? (y/n)${NC}"
    read -r response
    
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        for migration in $MIGRATIONS_DIR/*.sql; do
            filename=$(basename "$migration")
            echo -e "${YELLOW}Applying: $filename${NC}"
            
            if [ "$DOCKER_MODE" = true ]; then
                docker exec -i pulse-postgres psql -U "$DB_USER" -d "$DB_NAME" < "$migration"
            else
                $DB_CONNECTION -f "$migration"
            fi
            
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}✓ $filename applied${NC}"
            else
                echo -e "${RED}✗ Failed to apply $filename${NC}"
                echo -e "${YELLOW}Continue with remaining migrations? (y/n)${NC}"
                read -r continue_response
                if [[ ! "$continue_response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
                    exit 1
                fi
            fi
        done
        
        echo ""
        echo -e "${GREEN}=== Migration process complete ===${NC}"
    else
        echo "Migration cancelled"
    fi
fi
