# Pryojon Backend — Local Setup Guide

Run and verify the backend on your machine **before** deploying to cPanel.

## 1. Prerequisites

- **Node.js 18+** and **npm 9+** — verify: `node -v && npm -v`
- **MySQL 8** locally (XAMPP / Laragon / MAMP / Docker / Homebrew all work). Alternatively, point at the remote cPanel MySQL — but most ISPs block port 3306 from outside, so a local DB is recommended for first run.
- A REST client (curl, Postman, Insomnia, or Thunder Client).

## 2. Get the code

Unzip the delivered `pryojon-backend.zip` somewhere, then:

```bash
cd pryojon-backend
npm install
```

## 3. Create the `.env`

Copy the template:

```bash
cp .env.example .env
```

Edit `.env`:

```dotenv
# ----- Server -----
PORT=4000
NODE_ENV=development
CORS_ORIGIN=http://localhost:8080,http://localhost:5173
PUBLIC_BASE_URL=http://localhost:4000
UPLOAD_DIR=./uploads

# ----- Database (LOCAL MySQL example) -----
DATABASE_URL="mysql://root:@127.0.0.1:3306/pryojon_local"

# ----- JWT -----
JWT_SECRET=replace-with-a-long-random-string
JWT_EXPIRES_IN=7d

# ----- SMTP (dummy — replace later) -----
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=changeme
SMTP_PASS=changeme
SMTP_FROM="Pryojon <no-reply@example.com>"
```

Generate a strong JWT secret:
```bash
node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
```

## 4. Create the database

### Option A — Local MySQL + raw SQL (fastest)

```sql
CREATE DATABASE pryojon_local CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```
Then import the schema:
```bash
mysql -u root pryojon_local < sql/pryojon_mysql_schema.sql
```

### Option B — Prisma manages the schema

```bash
npx prisma generate
npx prisma db push        # creates tables from schema.prisma
npx prisma db seed        # optional sample rows
```

> If you want migration history, run `npx prisma migrate dev --name init` instead of `db push`.

### Option C — Point at the remote cPanel DB

Set `DATABASE_URL` to the cPanel connection string. Many shared hosts block remote MySQL — if `prisma db push` hangs or you get `P1001`, you cannot reach the DB from your laptop. Import the SQL via cPanel → phpMyAdmin instead and skip to step 5.

## 5. Run the server

```bash
npm run dev
```

Expected output:
```
[pryojon-backend] listening on :4000
```

Health check:
```bash
curl http://localhost:4000/api/health
# {"ok":true,"ts":1719...}
```

## 6. Smoke test (copy-paste)

```bash
# Register
curl -s -X POST http://localhost:4000/api/auth/signup \
  -H "Content-Type: application/json" \
  -d '{"email":"test@pryojon.local","password":"test1234","display_name":"Tester"}' | tee /tmp/signup.json

# Extract token
TOKEN=$(node -e "console.log(require('/tmp/signup.json').access_token)")
echo "TOKEN=$TOKEN"

# Me
curl -s http://localhost:4000/api/auth/me -H "Authorization: Bearer $TOKEN"

# List services (empty array on a fresh DB is fine)
curl -s http://localhost:4000/api/services

# Claim first admin (only works if no admin exists yet)
curl -s -X POST http://localhost:4000/api/user-roles/claim-first-admin -H "Authorization: Bearer $TOKEN"
```

## 7. Import the Postman collection

Open Postman → Import → select `POSTMAN_collection.json`. Set the `baseUrl` variable to `http://localhost:4000`. The Login request auto-stores the JWT into `{{token}}`.

## 8. Common errors

| Symptom | Cause | Fix |
|---|---|---|
| `P1001 Can't reach database server` | DB not running or wrong host | Start MySQL; check `DATABASE_URL` |
| `Error: Environment variable not found: DATABASE_URL` | `.env` not loaded | Ensure `.env` is in `backend/` and you run `npm run dev` from there |
| `JsonWebTokenError: secret or public key must be provided` | `JWT_SECRET` missing | Set it in `.env` and restart |
| `EADDRINUSE :::4000` | Port busy | Change `PORT=` or kill the other process |
| `CORS blocked` | Frontend origin not in `CORS_ORIGIN` | Add it to the comma-separated list and restart |
| `prisma db push` hangs | Remote DB unreachable | Use local MySQL, or import SQL via phpMyAdmin |
| Email never arrives on forgot-password | Dummy SMTP | Set real `SMTP_*` values; check server logs |

## 9. When local is green

1. Verify a full flow: signup → login → claim-first-admin → create category → create service.
2. Deploy to cPanel using `MIGRATION_GUIDE.md`.
3. Send the production URL back — you'll then start **Phase 2** (frontend migration off Supabase).

## File layout reference

```
backend/
├─ .env.example
├─ API_REFERENCE.md
├─ LOCAL_SETUP.md
├─ MIGRATION_GUIDE.md          # cPanel deploy
├─ POSTMAN_collection.json
├─ README.md
├─ package.json
├─ prisma/
│  ├─ schema.prisma
│  └─ seed.js
├─ sql/pryojon_mysql_schema.sql
└─ src/
   ├─ server.js
   ├─ lib/ (auth, prisma, mailer, codes, asyncHandler)
   └─ routes/ (auth, services, sellers, ...)
```
