# Swavroski Market v3 — Install & Deploy Guide

## 1. Local development (macOS / Linux)

### Prereqs
- Node.js ≥ 18 LTS
- MySQL 8 (or MariaDB 10.5+)

### First-time setup
```bash
# 1. Install dependencies
npm install

# 2. Start MySQL (macOS/Homebrew)
brew services start mysql

# 3. Create database + apply schema
mysql -u root -e "CREATE DATABASE IF NOT EXISTS swavroski_market CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -u root swavroski_market < schema.sql

# 4. Configure .env
cp .env .env.local   # keep a backup of your existing .env
# Edit .env: fill BOT_TOKEN, ADMIN_CHAT_ID, DB_USER, DB_PASS, wallet addresses.
# Set USE_WEBHOOK=false for local (polling mode).

# 5. Run the bot
npm start
```

On success you should see:
```
[server] listening on :3000
[db] connected to 127.0.0.1:3306/swavroski_market
[admin] bootstrapped super_admin: <your chat_id>
[bot] polling @YourBotUsername
```

Message your bot on Telegram → `/start` → home dashboard appears.

---

## 2. cPanel deployment (Node.js + MySQL)

### 2.1 Create the MySQL database
In cPanel → *MySQL® Databases*:
1. Create database `<prefix>_swavroski_market`.
2. Create a user and add it to the database with ALL PRIVILEGES.
3. Note the credentials — you'll need them in `.env`.

### 2.2 Upload the project
Upload the contents of this directory to a folder like `~/swavroski_bot/` in your cPanel home. Exclude `node_modules/` — cPanel will install dependencies for you.

Required files at that path:
- `server.js`, `app.js`, `package.json`, `schema.sql`, `.env`, `src/`, `chat_ids.txt`

### 2.3 Apply the schema
In cPanel → *phpMyAdmin*:
1. Open your database.
2. *Import* → choose `schema.sql` → *Go*.

### 2.4 Create the Node.js application
In cPanel → *Setup Node.js App*:
- **Node.js version**: latest LTS (18 or 20).
- **Application mode**: `Production`.
- **Application root**: the folder you uploaded to (e.g. `swavroski_bot`).
- **Application URL**: the domain / subdomain (HTTPS required for webhook).
- **Application startup file**: `server.js`.

Click *Create*, then *Run NPM Install* to populate `node_modules/`.

### 2.5 Fill `.env` on cPanel
Use *File Manager* → edit `.env`:
```
BOT_TOKEN=... (from @BotFather)
ADMIN_CHAT_ID=... (your Telegram numeric id)

DB_HOST=localhost
DB_PORT=3306
DB_USER=<cpanel_user>_bot
DB_PASS=<db_password>
DB_NAME=<cpanel_user>_swavroski_market

USE_WEBHOOK=true
WEBHOOK_BASE_URL=https://your-bot.example.com
WEBHOOK_SECRET=pick-a-long-random-string

PORT=3000
NODE_ENV=production

# wallet addresses
BTC_WALLET=bc1q...
USDT_WALLET=T...
ETH_WALLET=0x...
LTC_WALLET=L...
USDC_WALLET=0x...
```

### 2.6 Start the app
In *Setup Node.js App* → *Start App*. Watch the log (tail `~/logs/<app>.log` or the panel).

On first boot the bot will:
1. Connect to MySQL.
2. Bootstrap `ADMIN_CHAT_ID` as `super_admin` in the `admins` table.
3. Call `setWebHook(WEBHOOK_BASE_URL/webhook/WEBHOOK_SECRET)`.
4. Begin processing updates as Telegram POSTs them.

### 2.7 Verify webhook
```
curl https://your-bot.example.com/healthz
# {"ok":true,"mode":"webhook"}
```

Telegram status:
```
curl "https://api.telegram.org/bot<BOT_TOKEN>/getWebhookInfo"
```
Expect `url` to match `WEBHOOK_BASE_URL/webhook/WEBHOOK_SECRET`, `pending_update_count` small.

### 2.8 Optional: PM2
If your cPanel exposes shell access:
```bash
npm i -g pm2
pm2 start server.js --name swavroski
pm2 save
pm2 startup
```

---

## 3. Updating

Pull new code → `npm install` if deps changed → restart via cPanel *Restart App* or `pm2 restart swavroski`.

For schema migrations, add ALTER statements to `schema.sql` with `IF NOT EXISTS` guards and re-import via phpMyAdmin.

---

## 4. Switching between webhook and polling

`USE_WEBHOOK=true` → `server.js` calls `setWebHook` and Telegram POSTs to `/webhook/<secret>`.

`USE_WEBHOOK=false` → `server.js` calls `deleteWebHook` and the bot polls Telegram directly. Use this for local development; Telegram rejects updates when both are active.

---

## 5. Directory layout

```
swavroski_bot/
├── server.js                    # entry — boots Express + webhook/polling
├── app.js                       # Express app + /webhook + /healthz
├── schema.sql                   # MySQL DDL
├── package.json
├── .env                         # runtime config (not committed)
├── chat_ids.txt                 # auto-populated broadcast source
└── src/
    ├── config/
    │   ├── env.js               # dotenv loader + validation
    │   ├── db.js                # mysql2 pool + query/one/tx helpers
    │   └── bot.js               # node-telegram-bot-api instance
    ├── controllers/             # event → service wiring
    │   ├── userController.js    # /start /shop /wallet, inline shop nav
    │   ├── paymentController.js # deposit flow + admin decisions
    │   ├── productController.js # add/edit/delete product flows
    │   ├── orderController.js   # reply button + /reply command
    │   ├── adminController.js   # dashboard + add-staff + broadcast
    │   └── router.js            # /cancel, home-bar, session + callback dispatch
    ├── services/                # pure business logic (DB-aware)
    │   ├── walletService.js
    │   ├── paymentService.js
    │   ├── orderService.js
    │   ├── deliveryService.js
    │   ├── productService.js
    │   ├── broadcastService.js
    │   └── adminService.js
    ├── middlewares/
    │   ├── authMiddleware.js    # ensureUser + chat_id tracking
    │   └── roleMiddleware.js    # require admin / super admin guards
    ├── routes/
    │   └── webhook.js           # POST /webhook/<secret>
    ├── ui/
    │   ├── keyboards.js         # reply + inline keyboard factories
    │   ├── messages.js          # text templates (HTML-safe)
    │   └── catalog.js           # static category taxonomy
    └── utils/
        ├── logger.js
        ├── validator.js
        ├── queue.js             # rate-limited broadcast batcher + retry
        └── sessions.js          # in-memory per-user flow state
```
