# Ranchlands — Deployment Guide
## Stack: MariaDB + NGINX + Node.js on port 8584

---

## 1. Create the MariaDB database

Log into MariaDB as root and run:

```sql
CREATE DATABASE ranchlands CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'ranchlands'@'localhost' IDENTIFIED BY 'your_strong_password';
GRANT ALL PRIVILEGES ON ranchlands.* TO 'ranchlands'@'localhost';
FLUSH PRIVILEGES;
```

---

## 2. Install Node.js (if not already installed)

```bash
# Using nvm (recommended — lets you manage Node versions)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20
node --version   # should print v20.x.x
```

---

## 3. Clone and install

```bash
cd /var/www
git clone <your-repo-url> ranchlands
cd ranchlands
npm install
```

---

## 4. Configure environment

```bash
cp server/.env.example server/.env
nano server/.env
```

Fill in your actual values:

```env
PORT=8584
NODE_ENV=production

DB_HOST=localhost
DB_PORT=3306
DB_USER=ranchlands
DB_PASSWORD=your_strong_password
DB_NAME=ranchlands

# Generate secrets with:
# node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
JWT_SECRET=<64-char-hex>
REFRESH_TOKEN_SECRET=<64-char-hex>

CLIENT_URL=https://yourdomain.com
```

---

## 5. Run migrations and seed

```bash
npm run db:migrate    # creates all tables
npm run db:seed       # creates starter shows and season
```

---

## 6. Build the React frontend

```bash
npm run build --workspace=client
# Output will be in client/dist/
```

Copy the build to your web root:

```bash
sudo mkdir -p /var/www/ranchlands-web
sudo cp -r client/dist/* /var/www/ranchlands-web/
sudo chown -R www-data:www-data /var/www/ranchlands-web
```

---

## 7. Install and configure PM2

```bash
npm install -g pm2

# Start the Node server
pm2 start ecosystem.config.js --env production

# Verify it's running
pm2 status
pm2 logs ranchlands --lines 50

# Set PM2 to auto-start on server reboot
pm2 startup         # follow the command it prints
pm2 save
```

To check the API is responding:
```bash
curl http://localhost:8584/health
# Should return: {"status":"ok","version":"1.0.0",...}
```

---

## 8. Configure NGINX

```bash
# Copy the config
sudo cp /var/www/ranchlands/nginx.conf /etc/nginx/sites-available/ranchlands

# Edit it — update server_name and root path
sudo nano /etc/nginx/sites-available/ranchlands

# Important changes:
#   server_name yourdomain.com;       ← your actual domain or IP
#   root /var/www/ranchlands-web;     ← where you copied the client/dist files

# Enable the site
sudo ln -s /etc/nginx/sites-available/ranchlands /etc/nginx/sites-enabled/

# Test the config
sudo nginx -t

# If it passes, reload NGINX
sudo systemctl reload nginx
```

If you don't have a domain yet and just want to test on the server's IP,
change `listen 443 ssl http2` to `listen 80` and remove the SSL redirect block.

---

## 9. (Optional) SSL with Let's Encrypt

```bash
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com

# Certbot will automatically update your nginx config and handle renewals
```

---

## Day-to-day commands

| Task | Command |
|------|---------|
| Check server status | `pm2 status` |
| View live logs | `pm2 logs ranchlands` |
| Restart after code change | `pm2 restart ranchlands` |
| Stop server | `pm2 stop ranchlands` |
| Run new migrations | `npm run db:migrate` |
| Rebuild frontend | `npm run build --workspace=client && sudo cp -r client/dist/* /var/www/ranchlands-web/` |
| Reload NGINX | `sudo systemctl reload nginx` |
| Check NGINX errors | `sudo tail -f /var/log/nginx/ranchlands_error.log` |

---

## Firewall (if using ufw)

```bash
# NGINX handles all external traffic — Node doesn't need to be publicly exposed
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Port 8584 stays internal — NGINX proxies to it on localhost only
```

---

## Troubleshooting

**`pm2 logs` shows DB connection error:**
- Double-check `DB_PASSWORD` in `server/.env`
- Confirm the MariaDB user exists: `mysql -u ranchlands -p ranchlands`

**NGINX returns 502 Bad Gateway:**
- Node isn't running — check `pm2 status` and `pm2 logs`
- Make sure `proxy_pass http://127.0.0.1:8584` matches your PORT

**Frontend loads but API calls fail (404/CORS):**
- Make sure `/api/` block in nginx.conf is present and NGINX reloaded
- Check `CLIENT_URL` in `.env` matches the domain you're hitting from

**`npm run db:migrate` fails:**
- Verify DB credentials in `.env`
- Make sure the `ranchlands` database exists and the user has GRANT ALL on it
