#!/usr/bin/env bash
# =============================================================
# SMM Panel – Production Deployment Script
# Usage: chmod +x deploy.sh && sudo ./deploy.sh
# =============================================================

set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
ok()   { echo -e "${GREEN}✓ $*${NC}"; }
warn() { echo -e "${YELLOW}⚠ $*${NC}"; }
info() { echo -e "${CYAN}→ $*${NC}"; }
fail() { echo -e "${RED}✗ $*${NC}"; exit 1; }

echo -e "\n${CYAN}╔══════════════════════════════════════╗"
echo    "║   SMM Panel – Production Deploy      ║"
echo -e "╚══════════════════════════════════════╝${NC}\n"

# ── Require root ──────────────────────────────────────────
[[ $EUID -ne 0 ]] && fail "Run as root: sudo ./deploy.sh"

# ── Variables ─────────────────────────────────────────────
INSTALL_DIR="/var/www/smm-panel"
APP_USER="smmadmin"
DOMAIN="${DOMAIN:-yourdomain.com}"

# ── System packages ───────────────────────────────────────
info "Installing system packages..."
apt-get update -qq
apt-get install -y -qq curl git nginx certbot python3-certbot-nginx ufw redis-server mysql-server
ok "Packages installed"

# ── Node.js 20 ────────────────────────────────────────────
if ! command -v node &>/dev/null; then
  info "Installing Node.js 20..."
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  apt-get install -y -qq nodejs
fi
ok "Node.js $(node -v)"

# ── PM2 ───────────────────────────────────────────────────
npm install -g pm2 -q
ok "PM2 installed"

# ── App user ─────────────────────────────────────────────
if ! id "$APP_USER" &>/dev/null; then
  useradd -m -s /bin/bash "$APP_USER"
  ok "User $APP_USER created"
fi

# ── Install dir ───────────────────────────────────────────
mkdir -p "$INSTALL_DIR"
cp -r . "$INSTALL_DIR/"
chown -R "$APP_USER:$APP_USER" "$INSTALL_DIR"

# ── API dependencies ─────────────────────────────────────
info "Installing API dependencies..."
cd "$INSTALL_DIR/api"
sudo -u "$APP_USER" npm install --production --quiet
ok "API dependencies installed"

# ── Frontend build ────────────────────────────────────────
info "Building frontend..."
cd "$INSTALL_DIR/frontend"
sudo -u "$APP_USER" npm install --quiet
sudo -u "$APP_USER" npm run build
ok "Frontend built → public_html/"

# ── .env setup ───────────────────────────────────────────
if [[ ! -f "$INSTALL_DIR/api/.env" ]]; then
  cp "$INSTALL_DIR/api/.env.example" "$INSTALL_DIR/api/.env"
  JWT_SECRET=$(openssl rand -hex 32)
  DB_PASS=$(openssl rand -hex 16)
  sed -i "s/CHANGE_THIS_TO_A_STRONG_64_CHAR_RANDOM_SECRET/$JWT_SECRET/" "$INSTALL_DIR/api/.env"
  sed -i "s/STRONG_RANDOM_PASSWORD_HERE/$DB_PASS/"                       "$INSTALL_DIR/api/.env"
  warn ".env created — review and update: $INSTALL_DIR/api/.env"
fi

# ── MySQL setup ───────────────────────────────────────────
info "Configuring MySQL..."
source "$INSTALL_DIR/api/.env"
mysql -u root <<SQL
CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;
SQL
mysql -u root "$DB_NAME" < "$INSTALL_DIR/api/database/schema.sql"
cd "$INSTALL_DIR/api" && node database/seed.js
ok "Database configured and seeded"

# ── Redis ────────────────────────────────────────────────
systemctl enable redis-server --quiet
systemctl start redis-server
ok "Redis running"

# ── Nginx ────────────────────────────────────────────────
info "Configuring Nginx..."
sed "s/yourdomain.com/$DOMAIN/g" "$INSTALL_DIR/nginx/smm-panel.conf" > /etc/nginx/sites-available/smm-panel
ln -sf /etc/nginx/sites-available/smm-panel /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx
ok "Nginx configured"

# ── Firewall ─────────────────────────────────────────────
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw --force enable
ok "Firewall configured"

# ── SSL ──────────────────────────────────────────────────
if [[ "$DOMAIN" != "yourdomain.com" ]]; then
  info "Obtaining SSL certificate for $DOMAIN..."
  certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos -m "admin@$DOMAIN" --redirect
  ok "SSL certificate installed"
else
  warn "Skipped SSL — update DOMAIN variable before deployment"
fi

# ── PM2 startup ──────────────────────────────────────────
info "Starting API with PM2..."
cd "$INSTALL_DIR"
sudo -u "$APP_USER" NODE_ENV=production pm2 start ecosystem.config.js --env production
sudo -u "$APP_USER" pm2 save
pm2 startup systemd -u "$APP_USER" --hp "/home/$APP_USER" | tail -1 | bash
ok "PM2 service registered"

echo -e "\n${GREEN}╔════════════════════════════════════════════╗"
echo    "║    🚀 SMM Panel Deployed Successfully!    ║"
echo -e "╚════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  URL:        ${CYAN}https://$DOMAIN${NC}"
echo -e "  Admin:      ${CYAN}admin@smmpanel.com${NC}"
echo -e "  Password:   ${CYAN}Admin@1234${NC}  (change immediately!)"
echo -e "  API Docs:   ${CYAN}https://$DOMAIN/api-access${NC}"
echo ""
echo -e "  PM2 status: ${YELLOW}pm2 status${NC}"
echo -e "  API logs:   ${YELLOW}pm2 logs smm-panel-api${NC}"
echo ""
