#!/bin/bash
# scripts/deploy-hetzner.sh
# Run this on a fresh Hetzner Ubuntu 22.04 VPS
# Usage: bash deploy-hetzner.sh yourdomain.com admin@yourdomain.com

set -e

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

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║  Content Machine — Hetzner Deployment    ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "Domain: $DOMAIN"
echo "App dir: $APP_DIR"
echo ""

# ── 1. System update ──────────────────────────────────────────────
echo "→ Updating system..."
apt-get update -qq && apt-get upgrade -y -qq

# ── 2. Node.js 20 ─────────────────────────────────────────────────
echo "→ Installing Node.js 20..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs

# ── 3. PostgreSQL ──────────────────────────────────────────────────
echo "→ Installing PostgreSQL..."
apt-get install -y postgresql postgresql-contrib

# Create DB + user
DB_PASSWORD=$(openssl rand -hex 16)
sudo -u postgres psql <<EOF
CREATE USER contentmachine WITH PASSWORD '$DB_PASSWORD';
CREATE DATABASE contentmachine OWNER contentmachine;
GRANT ALL PRIVILEGES ON DATABASE contentmachine TO contentmachine;
EOF

echo "✓ PostgreSQL: DB password = $DB_PASSWORD (save this!)"

# ── 4. Redis ───────────────────────────────────────────────────────
echo "→ Installing Redis..."
apt-get install -y redis-server
systemctl enable redis-server
systemctl start redis-server

# ── 5. Nginx ───────────────────────────────────────────────────────
echo "→ Installing Nginx..."
apt-get install -y nginx

# ── 6. Certbot (SSL) ───────────────────────────────────────────────
echo "→ Installing Certbot..."
apt-get install -y certbot python3-certbot-nginx
certbot --nginx -d "$DOMAIN" -d "www.$DOMAIN" --non-interactive --agree-tos --email "$EMAIL" || echo "⚠ SSL setup failed — run manually after DNS is configured"

# ── 7. PM2 ─────────────────────────────────────────────────────────
echo "→ Installing PM2..."
npm install -g pm2

# ── 8. App directory ───────────────────────────────────────────────
echo "→ Setting up app directory..."
mkdir -p "$APP_DIR"
mkdir -p "$APP_DIR/backend/logs"

# ── 9. Nginx config ────────────────────────────────────────────────
echo "→ Configuring Nginx..."
cp nginx/contentmachine.conf /etc/nginx/sites-available/contentmachine
sed -i "s/yourdomain.com/$DOMAIN/g" /etc/nginx/sites-available/contentmachine
ln -sf /etc/nginx/sites-available/contentmachine /etc/nginx/sites-enabled/contentmachine
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx

# ── 10. Firewall ───────────────────────────────────────────────────
echo "→ Configuring firewall..."
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw --force enable

echo ""
echo "╔══════════════════════════════════════════════════════════╗"
echo "║  Server setup complete!                                  ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo ""
echo "Next steps:"
echo ""
echo "1. Upload your code:"
echo "   rsync -avz --exclude node_modules . root@SERVER_IP:$APP_DIR/"
echo ""
echo "2. Configure backend .env:"
echo "   nano $APP_DIR/backend/.env"
echo "   (copy from .env.example, fill in all values)"
echo "   DATABASE_URL=postgresql://contentmachine:$DB_PASSWORD@localhost:5432/contentmachine"
echo ""
echo "3. Install dependencies + run migrations:"
echo "   cd $APP_DIR/backend && npm install"
echo "   psql postgresql://contentmachine:$DB_PASSWORD@localhost:5432/contentmachine < migrations/001_initial.sql"
echo ""
echo "4. Build frontend:"
echo "   cd $APP_DIR/frontend && npm install && npm run build"
echo ""
echo "5. Start backend with PM2:"
echo "   cd $APP_DIR/backend && pm2 start ecosystem.config.cjs"
echo "   pm2 save && pm2 startup"
echo ""
echo "6. Configure Stripe webhook:"
echo "   Stripe Dashboard → Developers → Webhooks"
echo "   Endpoint URL: https://$DOMAIN/api/stripe/webhook"
echo "   Events: checkout.session.completed, invoice.payment_succeeded,"
echo "            invoice.payment_failed, customer.subscription.*"
echo ""
echo "7. Create superadmin user:"
echo "   cd $APP_DIR/backend && node scripts/create-superadmin.js"
echo ""
