#!/bin/bash

# ParentFlow Production Stop Script
# Stops PM2 processes and Docker containers gracefully

set -e

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "=========================================="
echo "Stopping ParentFlow Production"
echo "=========================================="
echo ""

# Step 1: Stop PM2 processes
echo -e "${BLUE}Step 1: Stopping PM2 processes...${NC}"
if command -v pm2 &> /dev/null; then
    pm2 stop all 2>/dev/null || true
    echo -e "${GREEN}✓ PM2 processes stopped${NC}"
else
    echo -e "${YELLOW}Warning: PM2 not found${NC}"
fi

# Step 2: Stop Docker containers
echo ""
echo -e "${BLUE}Step 2: Stopping Docker containers...${NC}"
if docker compose version &> /dev/null; then
    docker compose -f docker-compose.production.yml down
else
    docker-compose -f docker-compose.production.yml down 2>/dev/null || true
fi

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Docker containers stopped${NC}"
else
    echo -e "${YELLOW}Warning: Failed to stop some Docker containers${NC}"
fi

# Verify everything is stopped
echo ""
echo -e "${BLUE}Verification:${NC}"

# Check PM2
if command -v pm2 &> /dev/null; then
    RUNNING_PROCESSES=$(pm2 jlist 2>/dev/null | jq -r '.[] | select(.pm2_env.status == "online") | .name' | wc -l)
    if [ "$RUNNING_PROCESSES" -eq 0 ]; then
        echo -e "${GREEN}✓ No PM2 processes running${NC}"
    else
        echo -e "${YELLOW}Warning: $RUNNING_PROCESSES PM2 processes still running${NC}"
    fi
fi

# Check Docker
RUNNING_CONTAINERS=$(docker ps --filter name=parentflow --format "{{.Names}}" | wc -l)
if [ "$RUNNING_CONTAINERS" -eq 0 ]; then
    echo -e "${GREEN}✓ No ParentFlow Docker containers running${NC}"
else
    echo -e "${YELLOW}Warning: $RUNNING_CONTAINERS containers still running${NC}"
    docker ps --filter name=parentflow
fi

echo ""
echo "=========================================="
echo -e "${GREEN}Production environment stopped${NC}"
echo "=========================================="
echo ""
echo "To completely remove Docker volumes (WARNING: deletes data):"
echo "  docker-compose -f docker-compose.production.yml down -v"
echo ""
echo "To remove PM2 processes from startup:"
echo "  pm2 delete all"
echo "  pm2 save"