# Admin Setup & API Testing Guide

## 🔐 How to Create Admin Account

You have **3 options** to create an admin account:

### Option 1: Run the Seed Script (Recommended)

The easiest way is to run the seed script which creates:
- Super Admin account
- Primary member account
- Dependent member account
- Sample data for all modules

```bash
npm run seed
```

**Default Admin Credentials:**
- Username: `admin`
- Password: `Admin@123`

**Default Member Credentials:**
- Member ID: `1000` (Primary Member)
- Password: `Member@123`

- Member ID: `1000-w` (Dependent Wife)
- Password: `Member@123`

---

### Option 2: Create Admin Manually via MongoDB

If you want to create an admin manually without running the seed script:

#### Step 1: Connect to MongoDB

```bash
mongosh mongodb://localhost:27017/gym_khana_db
```

#### Step 2: Create Admin Role

```javascript
db.roles.insertOne({
  roleName: 'admin',
  description: 'Full system access, can manage all modules',
  createdAt: new Date(),
  updatedAt: new Date()
});
```

#### Step 3: Get the Role ID

```javascript
const adminRole = db.roles.findOne({ roleName: 'admin' });
console.log(adminRole._id);
```

#### Step 4: Create Admin User

First, generate a password hash. You can use this Node.js script:

```javascript
// hash-password.js
import bcrypt from 'bcryptjs';

const password = 'Admin@123';
const hash = await bcrypt.hash(password, 10);
console.log('Password Hash:', hash);
```

Run it:
```bash
node hash-password.js
```

Then create the admin user in MongoDB:

```javascript
db.users.insertOne({
  username: 'admin',
  email: 'admin@gymkhana.pk',
  passwordHash: 'PASTE_HASH_HERE', // Replace with hash from above
  role: adminRole._id,
  firstName: 'Super',
  lastName: 'Admin',
  phone: '0300-1234567',
  isActive: true,
  createdAt: new Date(),
  updatedAt: new Date()
});
```

---

### Option 3: Create Admin via API (If you have another admin)

If you already have an admin account and want to create another admin:

**Request:**
```http
POST http://localhost:3000/api/v1/users
Authorization: Bearer YOUR_ADMIN_TOKEN
Content-Type: application/json

{
  "username": "new_admin",
  "email": "newadmin@gymkhana.pk",
  "password": "Password@123",
  "firstName": "New",
  "lastName": "Admin",
  "phone": "0300-1234567",
  "roleId": "ADMIN_ROLE_ID",
  "isActive": true
}
```

---

## 📮 How to Use Postman Collection

### Step 1: Import the Collection

1. Open Postman
2. Click **Import** button
3. Select the file: `Gym_Khana_API.postman_collection.json`
4. Click **Import**

### Step 2: Set Up Environment (Optional but Recommended)

Create a new environment in Postman:

1. Click **Environments** in left sidebar
2. Click **+** to create new environment
3. Name it: `Gym Khana Local`
4. Add variables:
   - `baseUrl`: `http://localhost:3000/api/v1`
   - `accessToken`: (leave empty, will be auto-filled)

5. Click **Save**
6. Select this environment from the dropdown in top-right

### Step 3: Test the API

#### 1. Health Check (No Auth Required)

First, test if the API is running:
- Open: **Health Check** request
- Click **Send**
- You should get: `{ "success": true, "message": "API is running" }`

#### 2. Login as Admin

- Open: **1. Authentication → Staff Login**
- Body should have:
  ```json
  {
    "username": "admin",
    "password": "Admin@123"
  }
  ```
- Click **Send**
- If successful, the `accessToken` will be **automatically saved** to the environment variable
- All subsequent requests will use this token

#### 3. Test Protected Endpoints

Now you can test any protected endpoint. Examples:

**Get All Users:**
- Open: **2. User Management → Get All Users**
- Click **Send**
- You should see list of users

**Get All Members:**
- Open: **3. Member Management → Get All Members**
- Click **Send**
- You should see list of members

**Get Menu:**
- Open: **4. Restaurant - Menu → Get Menu**
- Click **Send**
- You should see menu items

#### 4. Login as Member

To test member-specific features:
- Open: **1. Authentication → Member Login**
- Body should have:
  ```json
  {
    "memberId": "1000",
    "password": "Member@123"
  }
  ```
- Click **Send**
- The member token will be saved

---

## 🎯 Quick Test Flow

### Flow 1: Create Restaurant Order

1. **Login as Admin** (or Restaurant Staff)
2. **Get Menu** - Note down some menu item IDs
3. **Get Tables** - Note down a table ID
4. **Create Order**:
   ```json
   {
     "memberId": "1000",
     "tableId": "table_id_here",
     "orderType": "Dine-In",
     "items": [
       {
         "menuItemId": "menu_item_id_here",
         "quantity": 2
       }
     ]
   }
   ```
5. **Get Orders** - Verify order was created
6. **Process Payment** - Choose Cash/Credit/Bank Transfer/Cheque

### Flow 2: Warehouse Stock Management

1. **Login as Admin** (or Warehouse Manager)
2. **Get Warehouse Items** - Note down item IDs
3. **Get Suppliers** - Note down supplier ID
4. **Stock In**:
   ```json
   {
     "warehouseItemId": "item_id_here",
     "quantity": 100,
     "purchasePrice": 150.00,
     "supplierId": "supplier_id_here",
     "notes": "Monthly purchase"
   }
   ```
5. **Get Stock Transactions** - Verify transaction
6. **Check Stock Alerts** - See low stock items

### Flow 3: Purchase Order Process

1. **Login as Admin** (or Warehouse Manager)
2. **Get Suppliers** - Note supplier ID
3. **Get Warehouse Items** - Note items to order
4. **Create Purchase Order**:
   ```json
   {
     "supplierId": "supplier_id_here",
     "orderDate": "2024-01-20",
     "expectedDeliveryDate": "2024-01-27",
     "items": [
       {
         "warehouseItemId": "item_id_1",
         "quantity": 100,
         "unitPrice": 150.00
       }
     ]
   }
   ```
5. **Update PO Status** to "Approved"
6. **Create GRN** when goods received - This auto-updates stock
7. **Verify Stock** - Check item stock increased

---

## 📊 Available Roles

The system has these roles with different permissions:

1. **admin** - Full system access
2. **front_desk** - Member management, check-in
3. **restaurant_staff** - Restaurant operations
4. **accountant** - Financial reports, transactions
5. **warehouse_manager** - Warehouse & inventory
6. **sports_manager** - Sports facilities (if implemented)
7. **member** - Member portal access

---

## 🔑 Important Notes

### Authentication

- All requests (except login and health check) require Bearer token
- Token is automatically set in Postman after login
- Token format: `Authorization: Bearer YOUR_TOKEN`

### Pagination

Most list endpoints support pagination:
```
?page=1&limit=20
```

### Filters

Many endpoints support filters:
- **Members**: `?status=Active`
- **Orders**: `?orderStatus=New&paymentStatus=Pending`
- **Warehouse**: `?category=Food&isActive=true`
- **Reports**: `?startDate=2024-01-01&endDate=2024-01-31`

### Response Format

All responses follow this format:
```json
{
  "success": true,
  "message": "Operation successful",
  "data": { ... },
  "timestamp": "2024-01-20T10:30:00.000Z"
}
```

### Error Format

```json
{
  "success": false,
  "message": "Error message here",
  "errors": null,
  "timestamp": "2024-01-20T10:30:00.000Z"
}
```

---

## 🚀 Getting Started Checklist

- [ ] MongoDB is running
- [ ] Run `npm install`
- [ ] Copy `.env.example` to `.env`
- [ ] Set `MONGODB_URI` in `.env`
- [ ] Run `npm run seed` to create admin and sample data
- [ ] Run `npm run dev` to start server
- [ ] Import Postman collection
- [ ] Create Postman environment (optional)
- [ ] Test health check endpoint
- [ ] Login as admin
- [ ] Start testing APIs!

---

## 📞 Support

If you face any issues:
1. Check server logs in terminal
2. Verify MongoDB is running: `mongosh mongodb://localhost:27017`
3. Check `.env` configuration
4. Verify you're using correct credentials
5. Make sure you have valid Bearer token for protected routes

---

## 🎉 You're All Set!

You now have:
- ✅ Admin account created
- ✅ Sample data in database
- ✅ Postman collection imported
- ✅ All APIs ready to test

**Happy Testing! 🚀**
