#!/bin/bash

# ParentFlow Production Deployment Script
# Run this on server 10.0.0.240 as root

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 "ParentFlow Production Deployment"
echo "=========================================="
echo ""

# Step 1: Check if already deployed
if [ -d "/root/maternal-app" ]; then
    echo -e "${YELLOW}Repository already exists. Pulling latest changes...${NC}"
    cd /root/maternal-app
    git pull origin main
else
    echo -e "${BLUE}Step 1: Cloning repository...${NC}"
    cd /root
    git clone https://git.noru1.ro/andrei/maternal-app.git
    cd maternal-app
fi

echo -e "${GREEN}✓ Repository ready${NC}"

# Step 2: Install Node.js if not present
echo ""
echo -e "${BLUE}Step 2: Checking Node.js installation...${NC}"
if ! command -v node &> /dev/null; then
    echo -e "${YELLOW}Installing Node.js 20...${NC}"
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
    apt-get install -y nodejs
fi
echo -e "${GREEN}✓ Node.js $(node -v)${NC}"

# Step 3: Install PM2 globally if not present
echo ""
echo -e "${BLUE}Step 3: Checking PM2 installation...${NC}"
if ! command -v pm2 &> /dev/null; then
    echo -e "${YELLOW}Installing PM2...${NC}"
    npm install -g pm2
fi
echo -e "${GREEN}✓ PM2 installed${NC}"

# Step 4: Install Docker and Docker Compose if not present
echo ""
echo -e "${BLUE}Step 4: Checking Docker installation...${NC}"
if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}Installing Docker...${NC}"
    curl -fsSL https://get.docker.com | sh
fi
echo -e "${GREEN}✓ Docker installed${NC}"

if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo -e "${YELLOW}Installing Docker Compose...${NC}"
    curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
fi
echo -e "${GREEN}✓ Docker Compose installed${NC}"

# Step 5: Install PostgreSQL client for migrations
echo ""
echo -e "${BLUE}Step 5: Installing PostgreSQL client...${NC}"
apt-get update
apt-get install -y postgresql-client
echo -e "${GREEN}✓ PostgreSQL client installed${NC}"

# Step 6: Install dependencies
echo ""
echo -e "${BLUE}Step 6: Installing application dependencies...${NC}"

echo -e "${YELLOW}Installing backend dependencies...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend
npm install

echo -e "${YELLOW}Installing frontend dependencies...${NC}"
cd /root/maternal-app/maternal-web
npm install

echo -e "${GREEN}✓ Dependencies installed${NC}"

# Step 7: Build applications
echo ""
echo -e "${BLUE}Step 7: Building applications...${NC}"

echo -e "${YELLOW}Building backend...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend
npm run build

echo -e "${YELLOW}Building frontend...${NC}"
cd /root/maternal-app/maternal-web
npm run build

echo -e "${GREEN}✓ Applications built${NC}"

# Step 8: Create .env.production if it doesn't exist
echo ""
echo -e "${BLUE}Step 8: Setting up environment variables...${NC}"
cd /root/maternal-app
if [ ! -f ".env.production" ]; then
    cp .env.production.example .env.production
    echo -e "${YELLOW}Created .env.production from example${NC}"
    echo -e "${RED}IMPORTANT: Edit .env.production with your actual values!${NC}"
    echo "Press Enter to continue after editing .env.production..."
    read
fi

# Step 9: Start Docker services
echo ""
echo -e "${BLUE}Step 9: Starting Docker services...${NC}"
cd /root/maternal-app
if docker compose version &> /dev/null; then
    docker compose -f docker-compose.production.yml up -d
else
    docker-compose -f docker-compose.production.yml up -d
fi
echo -e "${GREEN}✓ Docker services started${NC}"

# Step 10: Run database migrations
echo ""
echo -e "${BLUE}Step 10: Running database migrations...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend
chmod +x scripts/master-migration.sh scripts/check-migrations.sh

echo -e "${YELLOW}Testing database connection...${NC}"
PGPASSWORD=a3ppq psql -h 10.0.0.207 -p 5432 -U postgres -d parentflow -c "SELECT version();" > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Database connection successful${NC}"

    DATABASE_HOST=10.0.0.207 \
    DATABASE_PORT=5432 \
    DATABASE_NAME=parentflow \
    DATABASE_USER=postgres \
    DATABASE_PASSWORD=a3ppq \
    ./scripts/master-migration.sh
else
    echo -e "${RED}✗ Cannot connect to database${NC}"
    echo "Please check database server connectivity"
fi

# Step 11: Start PM2 processes
echo ""
echo -e "${BLUE}Step 11: Starting PM2 processes...${NC}"
cd /root/maternal-app
pm2 delete all 2>/dev/null || true
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup

echo -e "${GREEN}✓ PM2 processes started${NC}"

# Step 12: Verify deployment
echo ""
echo -e "${BLUE}Step 12: Verifying deployment...${NC}"
sleep 5

# Check if services are running
if lsof -i:3020 > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Backend is running on port 3020${NC}"
else
    echo -e "${RED}✗ Backend not detected on port 3020${NC}"
fi

if lsof -i:3030 > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Frontend is running on port 3030${NC}"
else
    echo -e "${RED}✗ Frontend not detected on port 3030${NC}"
fi

# Show status
echo ""
echo "=========================================="
echo -e "${GREEN}Deployment Complete!${NC}"
echo "=========================================="
echo ""
echo "Services:"
echo "  Backend API:  http://10.0.0.240:3020"
echo "  Frontend:     http://10.0.0.240:3030"
echo ""
echo "Public URLs (configure DNS/Nginx):"
echo "  API: https://api.parentflowapp.com → 10.0.0.240:3020"
echo "  Web: https://web.parentflowapp.com → 10.0.0.240:3030"
echo ""
echo "Management:"
echo "  PM2 status:     pm2 status"
echo "  PM2 logs:       pm2 logs"
echo "  Docker status:  docker ps"
echo ""
echo -e "${GREEN}✓ Production deployment successful!${NC}"