#!/bin/bash

# Deploy script for Biblical Guide production server
# Fetches latest code from production branch and deploys with PM2

set -e

echo "🚀 Starting deployment..."

# Configuration
REPO_URL="https://git.noru1.ro/andrei/ghidul-biblic.git"
BRANCH="production"
APP_NAME="ghidul-biblic"
PORT="3010"

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if .env file exists
if [ ! -f .env ]; then
    print_error ".env file not found. Please create it with required environment variables."
    exit 1
fi

# Validate required environment variables
print_status "Validating environment variables..."
required_vars=("DATABASE_URL" "JWT_SECRET" "AZURE_OPENAI_KEY" "AZURE_OPENAI_ENDPOINT")
missing_vars=()

for var in "${required_vars[@]}"; do
    if ! grep -q "^${var}=" .env; then
        missing_vars+=("$var")
    fi
done

if [ ${#missing_vars[@]} -ne 0 ]; then
    print_error "Missing required environment variables: ${missing_vars[*]}"
    exit 1
fi

print_success "Environment variables validated"

# Fetch latest code from production branch
print_status "Fetching latest code from $BRANCH branch..."
git fetch origin $BRANCH
git reset --hard origin/$BRANCH

print_success "Code updated to latest $BRANCH branch"

# Show current commit
CURRENT_COMMIT=$(git rev-parse --short HEAD)
COMMIT_MSG=$(git log -1 --pretty=format:"%s")
print_status "Current commit: $CURRENT_COMMIT - $COMMIT_MSG"

# Install dependencies if package.json changed
if git diff --name-only HEAD~1 HEAD | grep -q "package.json\|package-lock.json"; then
    print_status "Dependencies changed, installing..."
    npm ci
    print_success "Dependencies installed"
fi

# Build the application
print_status "Building application..."
npm run build

print_success "Application built successfully"

# Restart with PM2
print_status "Restarting application with PM2..."
pm2 restart $APP_NAME || pm2 start ecosystem.config.js --env production

# Save PM2 configuration
pm2 save

print_success "Application restarted with PM2"

# Wait for application to be ready
print_status "Waiting for application to start..."
sleep 5

# Health check
print_status "Performing health check..."
for i in {1..30}; do
    if curl -f http://localhost:$PORT/api/health >/dev/null 2>&1; then
        print_success "Application is healthy and running on port $PORT"
        break
    fi

    if [ $i -eq 30 ]; then
        print_error "Health check failed after 30 attempts"
        print_status "Showing PM2 logs:"
        pm2 logs $APP_NAME --lines 20
        exit 1
    fi

    sleep 2
done

# Show PM2 status
print_status "PM2 Status:"
pm2 status

print_success "🎉 Deployment completed successfully!"
print_status "Application is now running at: http://localhost:$PORT"
print_status "API health endpoint: http://localhost:$PORT/api/health"