#!/bin/bash
# ═══════════════════════════════════════════════════════════════════
# TheKetoBay — VPS Configuration Script
# Pokreni NAKON uploada fajlova na server
# Usage: bash configure-ketobay.sh theketobay.com your@email.com
# ═══════════════════════════════════════════════════════════════════

set -e
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; BLUE='\033[0;34m'; NC='\033[0m'
info()    { echo -e "${BLUE}ℹ️  $1${NC}"; }
success() { echo -e "${GREEN}✅ $1${NC}"; }
warn()    { echo -e "${YELLOW}⚠️  $1${NC}"; }

DOMAIN=${1:-"theketobay.com"}
EMAIL=${2:-"admin@theketobay.com"}
APP_DIR="/var/www/theketobay"

echo -e "${GREEN}"
echo "  ██╗  ██╗███████╗████████╗ ██████╗ ██████╗  █████╗ ██╗   ██╗"
echo "  ██║ ██╔╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔══██╗╚██╗ ██╔╝"
echo "  █████╔╝ █████╗     ██║   ██║   ██║██████╔╝███████║ ╚████╔╝ "
echo "  ██╔═██╗ ██╔══╝     ██║   ██║   ██║██╔══██╗██╔══██║  ╚██╔╝  "
echo "  ██║  ██╗███████╗   ██║   ╚██████╔╝██████╔╝██║  ██║   ██║   "
echo "  ╚═╝  ╚═╝╚══════╝   ╚═╝    ╚═════╝ ╚═════╝ ╚═╝  ╚═╝   ╚═╝  "
echo -e "${NC}"
echo -e "${GREEN}  🥑 TheKetoBay VPS Configurator${NC}"
echo -e "  Domain: ${YELLOW}$DOMAIN${NC}"
echo ""

# ── 1. Create app directory ────────────────────────────────────────
echo "📁 Setting up app directory at $APP_DIR..."
mkdir -p $APP_DIR
cd $APP_DIR

# ── 2. Check .env exists ───────────────────────────────────────────
if [ ! -f .env ]; then
  warn ".env not found — creating from example"
  if [ -f .env.example ]; then
    cp .env.example .env

    # Auto-fill some values
    JWT_SECRET=$(openssl rand -base64 64 | tr -d '\n')
    POSTGRES_PASS=$(openssl rand -base64 24 | tr -d '\n/+=' | head -c 20)
    REDIS_PASS=$(openssl rand -base64 16 | tr -d '\n/+=' | head -c 16)
    MINIO_PASS=$(openssl rand -base64 16 | tr -d '\n/+=' | head -c 16)

    sed -i "s|CHANGE_ME_STRONG_PASSWORD|$POSTGRES_PASS|g" .env
    sed -i "s|CHANGE_ME_REDIS_PASSWORD|$REDIS_PASS|g" .env
    sed -i "s|CHANGE_ME_MINIO_PASSWORD|$MINIO_PASS|g" .env
    sed -i "s|CHANGE_ME_VERY_LONG_RANDOM_STRING_AT_LEAST_64_CHARS|$JWT_SECRET|g" .env
    sed -i "s|https://theketobay.com|https://$DOMAIN|g" .env
    sed -i "s|noreply@theketobay.com|noreply@$DOMAIN|g" .env

    success "Generated: JWT_SECRET, POSTGRES_PASSWORD, REDIS_PASSWORD, MINIO_PASSWORD"
    warn "⚠️  Still needed in .env: STRIPE_SECRET_KEY, TELEGRAM_BOT_TOKEN, SMTP credentials"
    echo ""
    echo -e "${YELLOW}Open .env and fill in Stripe + Telegram:${NC}"
    echo "  nano $APP_DIR/.env"
    echo ""
    read -p "Press ENTER after editing .env to continue..."
  else
    error ".env.example not found. Did you upload the project files?"
  fi
fi

# ── 3. Create required directories ────────────────────────────────
mkdir -p infrastructure/nginx/conf.d
mkdir -p infrastructure/db-backup
mkdir -p infrastructure/certbot/www
mkdir -p infrastructure/certbot/conf

# ── 4. Nginx config — HTTP only first (for certbot challenge) ──────
echo "🔧 Configuring Nginx (HTTP first for SSL challenge)..."

cat > infrastructure/nginx/nginx-http.conf << NGINXEOF
events { worker_connections 1024; }
http {
  server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;
    location /.well-known/acme-challenge/ { root /var/www/certbot; }
    location / { return 200 'TheKetoBay loading...'; add_header Content-Type text/plain; }
  }
}
NGINXEOF

success "Nginx HTTP config created"

# ── 5. Start infrastructure services ──────────────────────────────
echo "🐳 Starting Docker services..."
docker compose -f infrastructure/docker-compose.yml up postgres redis minio -d

echo "⏳ Waiting for PostgreSQL..."
until docker exec ketobay_db pg_isready -U ketobay 2>/dev/null; do
  echo -n "."; sleep 2
done
success "PostgreSQL ready"

# ── 6. Install Node.js ─────────────────────────────────────────────
if ! command -v node &> /dev/null; then
  echo "📦 Installing Node.js 20..."
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  apt-get install -y nodejs
  success "Node.js $(node --version) installed"
else
  success "Node.js already installed: $(node --version)"
fi

# ── 7. Install npm dependencies ────────────────────────────────────
echo "📦 Installing npm dependencies..."
npm install --quiet
success "Dependencies installed"

# ── 8. Database setup ──────────────────────────────────────────────
echo "🗄️  Running database migrations..."
npm run db:generate 2>/dev/null || npx prisma generate --schema=packages/db/prisma/schema.prisma
NODE_ENV=production npx prisma migrate deploy --schema=packages/db/prisma/schema.prisma 2>/dev/null || \
  npx prisma db push --schema=packages/db/prisma/schema.prisma

echo "🌱 Seeding database..."
npm run db:seed 2>/dev/null || echo "Seed skipped"
success "Database ready"

# ── 9. Build apps ─────────────────────────────────────────────────
echo "🔨 Building applications..."
npm run build 2>/dev/null || warn "Build failed — will try Docker build"
success "Apps built"

# ── 10. SSL Certificate ───────────────────────────────────────────
echo ""
echo -e "${YELLOW}🔒 SSL Certificate Setup${NC}"
echo "Starting temporary Nginx for ACME challenge..."

# Start nginx with HTTP config
docker run -d --name nginx_temp \
  -p 80:80 \
  -v $(pwd)/infrastructure/certbot/www:/var/www/certbot:ro \
  -v $(pwd)/infrastructure/nginx/nginx-http.conf:/etc/nginx/nginx.conf:ro \
  nginx:alpine 2>/dev/null || true

sleep 3

# Get certificate
docker run --rm \
  -v $(pwd)/infrastructure/certbot/conf:/etc/letsencrypt \
  -v $(pwd)/infrastructure/certbot/www:/var/www/certbot \
  certbot/certbot certonly \
  --webroot \
  --webroot-path=/var/www/certbot \
  -d $DOMAIN \
  -d www.$DOMAIN \
  --email $EMAIL \
  --agree-tos \
  --no-eff-email \
  --non-interactive && SSL_OK=true || SSL_OK=false

docker stop nginx_temp 2>/dev/null && docker rm nginx_temp 2>/dev/null || true

if [ "$SSL_OK" = true ]; then
  success "SSL certificate obtained for $DOMAIN"
else
  warn "SSL failed — check DNS points to this server IP"
  warn "Continuing with HTTP only. Run ssl-setup.sh later."
fi

# ── 11. Start full stack ───────────────────────────────────────────
echo "🚀 Starting full TheKetoBay stack..."
docker compose -f infrastructure/docker-compose.yml up -d
success "All services started"

# ── 12. Ollama model ──────────────────────────────────────────────
echo ""
echo -e "${YELLOW}🤖 Pulling Ollama AI model...${NC}"
OLLAMA_MODEL=$(grep OLLAMA_MODEL .env | cut -d= -f2 | tr -d '"' | tr -d "'" || echo "llama3:8b")
echo "Model: $OLLAMA_MODEL"

# Wait for Ollama to start
sleep 5
docker exec ketobay_ollama ollama pull $OLLAMA_MODEL && \
  success "Model $OLLAMA_MODEL ready" || \
  warn "Model pull failed — run manually: docker exec ketobay_ollama ollama pull $OLLAMA_MODEL"

# ── 13. Setup systemd service ─────────────────────────────────────
echo "⚙️  Creating systemd service for auto-start..."

cat > /etc/systemd/system/theketobay.service << SVCEOF
[Unit]
Description=TheKetoBay Application Stack
Requires=docker.service
After=docker.service network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=$APP_DIR
ExecStart=/usr/bin/docker compose -f infrastructure/docker-compose.yml up -d
ExecStop=/usr/bin/docker compose -f infrastructure/docker-compose.yml down
StandardOutput=journal

[Install]
WantedBy=multi-user.target
SVCEOF

systemctl daemon-reload
systemctl enable theketobay
success "Systemd service created — will auto-start on reboot"

# ── 14. Setup log rotation ────────────────────────────────────────
cat > /etc/logrotate.d/theketobay << 'LOGEOF'
/var/log/theketobay/*.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
}
LOGEOF

# ── 15. Setup cron for cert renewal ──────────────────────────────
(crontab -l 2>/dev/null; echo "0 3 * * * docker run --rm -v $APP_DIR/infrastructure/certbot/conf:/etc/letsencrypt -v $APP_DIR/infrastructure/certbot/www:/var/www/certbot certbot/certbot renew --quiet && docker exec ketobay_nginx nginx -s reload") | crontab -
success "SSL auto-renewal cron set (daily at 3 AM)"

# ── Final status ──────────────────────────────────────────────────
echo ""
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo -e "${GREEN}  🥑 TheKetoBay deployment complete!${NC}"
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo ""
echo -e "🌐 Website:     ${GREEN}https://$DOMAIN${NC}"
echo -e "🔧 API health:  ${GREEN}https://$DOMAIN/api/health${NC}"
echo ""
echo -e "👤 Admin:       ${YELLOW}admin@theketobay.com${NC}"
echo -e "🔑 Password:    ${YELLOW}Admin123!${NC} (change this!)"
echo ""
echo "📋 Useful commands:"
echo "  docker compose -f $APP_DIR/infrastructure/docker-compose.yml logs -f"
echo "  docker compose -f $APP_DIR/infrastructure/docker-compose.yml ps"
echo "  docker exec ketobay_ollama ollama list"
echo ""
echo -e "${YELLOW}⚠️  Remember to change the admin password!${NC}"
echo -e "${YELLOW}⚠️  Set your Stripe webhook: https://$DOMAIN/api/payments/webhook${NC}"
