# Quick Start Guide

Get your Gym Khana Management System up and running in 5 minutes!

## Prerequisites

- Node.js v24.11.1+
- PostgreSQL 18+
- npm

## Step-by-Step Setup

### 1. Install Dependencies (1 minute)

```bash
npm install
```

### 2. Setup Environment (1 minute)

```bash
# Copy environment file
cp .env.example .env

# Edit .env with your database credentials
nano .env  # or use your favorite editor
```

**Required changes in .env**:
```env
DB_NAME=gym_khana_db
DB_USER=postgres
DB_PASSWORD=your_password
JWT_SECRET=change_this_to_a_random_secret_key
```

### 3. Create Database (1 minute)

```bash
# Connect to PostgreSQL
psql -U postgres

# Create database
CREATE DATABASE gym_khana_db;

# Exit
\q

# Import schema
psql -U postgres -d gym_khana_db -f database/schema.sql
```

### 4. Create Super Admin (1 minute)

```bash
npm run create-admin
```

Follow the prompts and create your admin account:
- Username: `admin`
- Password: `Admin@123` (or your choice)
- Email: `admin@gymkhana.pk`
- Name: Your name

### 5. Start Server (1 minute)

```bash
# Development mode
npm run dev

# Or production mode
npm start
```

You should see:
```
✅ Database connection established
🚀 Server running on port 3000
```

## Test Your Setup

### 1. Health Check

```bash
curl http://localhost:3000/api/v1/health
```

Expected response:
```json
{
  "success": true,
  "message": "API is running"
}
```

### 2. Login

```bash
curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "Admin@123"
  }'
```

Expected response:
```json
{
  "success": true,
  "message": "Login successful",
  "data": {
    "user": {
      "userId": 1,
      "username": "admin",
      "role": "admin"
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}
```

### 3. Save Your Token

Copy the `accessToken` from the response above. You'll use it in subsequent requests:

```bash
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInVzZXJuYW1lIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE3NjM1ODAyMjYsImV4cCI6MTc2MzY2NjYyNn0.1JsdP798k3vQfPgOks5feFKappJUEyVsKrWb2A6pV6w"
```

### 4. Test Protected Endpoint

```bash
curl http://localhost:3000/api/v1/auth/me \
  -H "Authorization: Bearer $TOKEN"
```

## Common Use Cases

### Register a New Member

```bash
curl -X POST http://localhost:3000/api/v1/members/register \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "memberId": "1001",
    "membershipTypeId": 1,
    "firstName": "Ahmed",
    "lastName": "Khan",
    "fatherName": "Muhammad Khan",
    "cnic": "4210112345678",
    "dateOfBirth": "1980-05-15",
    "gender": "Male",
    "phonePrimary": "03001234567",
    "email": "ahmed@example.com",
    "address": "House 123, Street 45, Hyderabad",
    "emergencyContactName": "Ali Khan",
    "emergencyContactPhone": "03331234567",
    "membershipStartDate": "2024-01-01",
    "password": "Member@123"
  }'
```

### Add Family Member

```bash
curl -X POST http://localhost:3000/api/v1/members/1001/family \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "Fatima",
    "lastName": "Ahmed",
    "relationToPrimary": "Spouse",
    "dateOfBirth": "1985-03-20",
    "gender": "Female",
    "cnic": "4210198765432",
    "password": "Spouse@123"
  }'
```

### Search Members

```bash
curl "http://localhost:3000/api/v1/members/search?q=Ahmed" \
  -H "Authorization: Bearer $TOKEN"
```

### Create Staff User

```bash
curl -X POST http://localhost:3000/api/v1/users \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "frontdesk1",
    "email": "frontdesk@gymkhana.pk",
    "password": "FrontDesk@123",
    "firstName": "Front",
    "lastName": "Desk",
    "phone": "03001234567",
    "role": "front_desk"
  }'
```

## Using Postman

### Import Collection

1. Open Postman
2. Click Import
3. Create a new collection named "Gym Khana API"
4. Set base URL: `http://localhost:3000/api/v1`
5. Add Authorization header: `Bearer {{token}}`

### Environment Variables

Create these variables in Postman:
- `base_url`: `http://localhost:3000/api/v1`
- `token`: (will be set after login)

### Save Token After Login

In the login request, add this to Tests tab:

```javascript
if (pm.response.code === 200) {
    const response = pm.response.json();
    pm.environment.set("token", response.data.accessToken);
}
```

## Troubleshooting

### Database Connection Error

**Error**: `Error: connect ECONNREFUSED 127.0.0.1:5432`

**Solution**:
1. Make sure PostgreSQL is running: `sudo systemctl start postgresql`
2. Check credentials in `.env` file
3. Verify database exists: `psql -U postgres -l`

### Port Already in Use

**Error**: `Error: listen EADDRINUSE: address already in use :::3000`

**Solution**:
1. Change PORT in `.env` file
2. Or kill the process using port 3000: `lsof -ti:3000 | xargs kill`

### JWT Error

**Error**: `Invalid or expired token`

**Solution**:
1. Make sure JWT_SECRET is set in `.env`
2. Login again to get a new token
3. Check token expiration time

### Schema Not Found

**Error**: `relation "users" does not exist`

**Solution**:
Run the schema again:
```bash
psql -U postgres -d gym_khana_db -f database/schema.sql
```

## Next Steps

1. ✅ Complete setup above
2. 📖 Read the full [README.md](README.md)
3. 🧪 Test all endpoints with Postman
4. 👥 Create users for different roles
5. 📊 Explore the API documentation: `http://localhost:3000/api/v1/docs`

## Need Help?

- Check [README.md](README.md) for detailed documentation
- Review API examples above
- Check server logs in `./logs` directory
- Ensure all prerequisites are installed

## Development Tips

### Watch Logs in Real-Time

```bash
# In a separate terminal
tail -f logs/combined.log
```

### Auto-Restart on Changes

Development mode with nodemon:
```bash
npm run dev
```

### Database Queries

View database content:
```bash
psql -U postgres -d gym_khana_db

# View members
SELECT * FROM members;

# View users
SELECT * FROM users;

# View roles
SELECT * FROM roles;
```

## Security Reminders

⚠️ **Before going to production:**

1. Change JWT_SECRET to a strong random string
2. Use strong passwords for database
3. Enable HTTPS
4. Configure proper CORS origins
5. Review rate limiting settings
6. Enable production logging
7. Set up regular database backups

---

**You're all set! Start building with the Gym Khana Management System API** 🚀
