#!/bin/bash
# deploy.sh - Deployment script for Press Zone Backend on dev1.press.zone
# Run this as user 'press' to pull latest changes and restart services

set -e  # Exit on error

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

# Configuration
PROJECT_DIR="$HOME/press-zone-backend"
LOG_FILE="$HOME/press-zone-backend/deploy.log"

# Functions
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1" | tee -a "$LOG_FILE"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1" | tee -a "$LOG_FILE"
}

# Check if running as user press
if [ "$(whoami)" != "press" ]; then
    error "This script must be run as user 'press'"
    exit 1
fi

log "Starting deployment process..."

# Navigate to project directory
cd "$PROJECT_DIR" || {
    error "Project directory not found: $PROJECT_DIR"
    exit 1
}

# Pull latest changes from git
log "Pulling latest changes from GitHub..."
git fetch origin
git pull origin master || {
    error "Failed to pull from GitHub"
    exit 1
}

# Install/update API dependencies
log "Installing API dependencies..."
cd "$PROJECT_DIR/api"
npm ci --production || {
    error "Failed to install API dependencies"
    exit 1
}

# Generate Prisma Client
log "Generating Prisma client..."
npx prisma generate || {
    error "Failed to generate Prisma client"
    exit 1
}

# Run database migrations
log "Running database migrations..."
npx prisma migrate deploy || {
    warn "Database migrations failed or no new migrations to apply"
}

# Build TypeScript
log "Building TypeScript..."
npm run build || {
    error "Failed to build TypeScript"
    exit 1
}

# Restart services using systemd
log "Restarting services..."
systemctl --user restart presszone-backend.service || {
    error "Failed to restart services"
    exit 1
}

# Wait for services to start
log "Waiting for services to start..."
sleep 5

# Health check
log "Performing health check..."
MAX_RETRIES=10
RETRY_COUNT=0

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if curl -f http://localhost:3000/health > /dev/null 2>&1; then
        log "Health check passed! API is responding."
        break
    else
        RETRY_COUNT=$((RETRY_COUNT + 1))
        if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
            error "Health check failed after $MAX_RETRIES attempts"
            systemctl --user status presszone-backend.service
            exit 1
        fi
        warn "Health check attempt $RETRY_COUNT failed, retrying in 3 seconds..."
        sleep 3
    fi
done

# Show service status
log "Deployment completed successfully!"
log "Service status:"
systemctl --user status presszone-backend.service --no-pager

log "Recent API logs:"
journalctl --user -u presszone-backend.service -n 20 --no-pager

log "Deployment finished at $(date)"
