#!/usr/bin/env bash
# Deploy Token Aggregation Service to Proxmox VM
# This script creates an LXC container and deploys the service with control panel

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SERVICE_DIR="$PROJECT_ROOT/smom-dbis-138/services/token-aggregation"

# Load common functions if available
if [[ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/lib/common.sh" ]]; then
  source "$PROJECT_ROOT/smom-dbis-138-proxmox/lib/common.sh"
fi

# Configuration
VMID="${VMID:-3600}"
HOSTNAME="${HOSTNAME:-token-aggregation}"
MEMORY="${MEMORY:-4096}"
CORES="${CORES:-2}"
DISK="${DISK:-40}"
IP_ADDRESS="${IP_ADDRESS:-}"

log_info "Deploying Token Aggregation Service to Proxmox VMID: $VMID"

# Check if running on Proxmox host
if ! command_exists pct 2>/dev/null; then
  log_error "This script must be run on Proxmox host (pct command not found)"
  exit 1
fi

# Check if container exists
if pct list | grep -q "^\s*$VMID\s"; then
  log_warn "Container $VMID already exists"
  read -p "Do you want to recreate it? (y/N): " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    log_info "Stopping and destroying existing container..."
    pct stop $VMID 2>/dev/null || true
    pct destroy $VMID || true
  else
    log_info "Using existing container $VMID"
    pct start $VMID 2>/dev/null || true
    exit 0
  fi
fi

# Create container
log_info "Creating LXC container $VMID..."
OS_TEMPLATE="${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}"

if [[ -n "$IP_ADDRESS" ]]; then
  NETWORK_CONFIG="bridge=vmbr0,name=eth0,ip=$IP_ADDRESS/24,gw=192.168.11.1"
else
  NETWORK_CONFIG="bridge=vmbr0,name=eth0,ip=dhcp"
fi

pct create "$VMID" \
  "$OS_TEMPLATE" \
  --storage local-lvm \
  --hostname "$HOSTNAME" \
  --memory "$MEMORY" \
  --cores "$CORES" \
  --rootfs local-lvm:"$DISK" \
  --net0 "$NETWORK_CONFIG" \
  --unprivileged 1 \
  --swap 1024 \
  --onboot 1 \
  --features nesting=1,keyctl=1

log_success "Container $VMID created"

# Start container
log_info "Starting container..."
pct start "$VMID"
sleep 5

# Wait for container to be ready
log_info "Waiting for container to be ready..."
for i in {1..30}; do
  if pct exec "$VMID" -- test -f /etc/os-release 2>/dev/null; then
    break
  fi
  sleep 2
done

# Update container
log_info "Updating container..."
pct exec "$VMID" -- bash -c "export DEBIAN_FRONTEND=noninteractive && apt-get update && apt-get upgrade -y"

# Install dependencies
log_info "Installing dependencies..."
pct exec "$VMID" -- bash -c "export DEBIAN_FRONTEND=noninteractive && apt-get install -y curl wget git build-essential postgresql-client"

# Install Node.js 20
log_info "Installing Node.js 20..."
pct exec "$VMID" -- bash -c "curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs"

# Install nginx for frontend
log_info "Installing nginx..."
pct exec "$VMID" -- bash -c "export DEBIAN_FRONTEND=noninteractive && apt-get install -y nginx"

# Create service user
log_info "Creating service user..."
pct exec "$VMID" -- bash -c "useradd -m -s /bin/bash token-aggregation || true"

# Create service directory
log_info "Setting up service directory..."
pct exec "$VMID" -- bash -c "mkdir -p /opt/token-aggregation && chown token-aggregation:token-aggregation /opt/token-aggregation"

# Copy service files
log_info "Copying service files..."
pct push "$VMID" "$SERVICE_DIR" /opt/token-aggregation --recursive

# Install service dependencies
log_info "Installing service dependencies..."
pct exec "$VMID" -- bash -c "cd /opt/token-aggregation && npm install"

# Build service
log_info "Building service..."
pct exec "$VMID" -- bash -c "cd /opt/token-aggregation && npm run build"

# Build frontend
log_info "Building frontend..."
pct exec "$VMID" -- bash -c "cd /opt/token-aggregation/frontend && npm install && npm run build"

# Create systemd service
log_info "Creating systemd service..."
pct exec "$VMID" -- bash -c "cat > /etc/systemd/system/token-aggregation.service << 'EOF'
[Unit]
Description=Token Aggregation Service
After=network.target

[Service]
Type=simple
User=token-aggregation
WorkingDirectory=/opt/token-aggregation
Environment=NODE_ENV=production
ExecStart=/usr/bin/node /opt/token-aggregation/dist/index.js
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
"

# Configure nginx for frontend
log_info "Configuring nginx..."
pct exec "$VMID" -- bash -c "cat > /etc/nginx/sites-available/token-aggregation << 'EOF'
server {
    listen 80;
    server_name _;

    # Frontend
    location / {
        root /opt/token-aggregation/frontend/dist;
        try_files \$uri \$uri/ /index.html;
    }

    # API proxy
    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOF
"

pct exec "$VMID" -- bash -c "ln -sf /etc/nginx/sites-available/token-aggregation /etc/nginx/sites-enabled/ && rm -f /etc/nginx/sites-enabled/default"

# Enable and start services
log_info "Enabling services..."
pct exec "$VMID" -- systemctl daemon-reload
pct exec "$VMID" -- systemctl enable token-aggregation
pct exec "$VMID" -- systemctl enable nginx
pct exec "$VMID" -- systemctl restart nginx

# Get container IP
CONTAINER_IP=$(pct exec "$VMID" -- hostname -I | awk '{print $1}')
log_success "Container IP: $CONTAINER_IP"

log_info "Deployment complete!"
log_info "Service will be available at: http://$CONTAINER_IP"
log_info "Control Panel: http://$CONTAINER_IP"
log_info ""
log_info "Next steps:"
log_info "1. Configure .env file in /opt/token-aggregation"
log_info "2. Run database migration"
log_info "3. Start service: systemctl start token-aggregation"
log_info "4. Create admin user via API or database"
