# Admin API Documentation

## Overview
The admin system provides a separate set of controllers and services for administrative operations. It includes a separate authentication system with its own admin users that are distinct from regular application users.

## Base URL
All admin endpoints are prefixed with `/admin`

## Authentication
The admin system uses JWT authentication. Admin tokens are separate from regular user tokens and include an `isAdmin` flag.

### Default Super Admin
On first startup, the system creates a default super admin account:
- Email: Set via `DEFAULT_ADMIN_EMAIL` env variable (default: `superadmin@example.com`)
- Password: Set via `DEFAULT_ADMIN_PASSWORD` env variable (default: `Admin@123456`)

**IMPORTANT**: Change the default password immediately after first login!

## Available Endpoints

### Admin Authentication

#### Login
- **POST** `/admin/auth/login`
  - Login with admin credentials
  
**Request Body:**
```json
{
  "email": "admin@example.com",
  "password": "password123"
}
```

**Response:**
```json
{
  "token": "jwt-token-here",
  "user": {
    "_id": "admin-id",
    "name": "Admin Name",
    "email": "admin@example.com",
    "role": "admin",
    "isActive": true,
    "permissions": [],
    "lastLoginAt": "2024-01-01T00:00:00Z"
  }
}
```

#### Register New Admin (Super Admin Only)
- **POST** `/admin/auth/register`
  - Create a new admin account
  - Requires: Super Admin role
  
**Request Body:**
```json
{
  "name": "New Admin",
  "email": "newadmin@example.com", 
  "password": "password123",
  "role": "admin",
  "permissions": ["users.read", "users.write"]
}
```

#### Get Current Admin Profile
- **GET** `/admin/auth/me`
  - Get current admin's profile
  - Requires: Admin authentication

#### Update Profile
- **PUT** `/admin/auth/me`
  - Update current admin's profile
  - Requires: Admin authentication

**Request Body:**
```json
{
  "name": "Updated Name",
  "permissions": ["users.read", "analytics.read"]
}
```

#### Change Password
- **POST** `/admin/auth/change-password`
  - Change current admin's password
  - Requires: Admin authentication

**Request Body:**
```json
{
  "oldPassword": "current-password",
  "newPassword": "new-password"
}
```

#### List All Admins (Super Admin Only)
- **GET** `/admin/auth/admins`
  - Get list of all admin users
  - Requires: Super Admin role

#### Toggle Admin Status (Super Admin Only)
- **PUT** `/admin/auth/admins/:id/toggle-status`
  - Enable/disable an admin account
  - Requires: Super Admin role

#### Delete Admin (Super Admin Only)
- **DELETE** `/admin/auth/admins/:id`
  - Permanently delete an admin account
  - Requires: Super Admin role

#### Logout
- **POST** `/admin/auth/logout`
  - Logout (client should remove token)
  - Requires: Admin authentication

### Dashboard
- **GET** `/admin/dashboard`
  - Returns aggregated statistics and analytics for the admin dashboard
  - Requires: Admin authentication

### Health Check
- **GET** `/admin/health`
  - Returns the health status of the admin system

### User Management

#### List Users with Pagination & Filtering
- **GET** `/admin/users`
  
**Query Parameters:**
- `page` (number, optional): Page number (default: 1)
- `limit` (number, optional): Items per page (default: 10)
- `search` (string, optional): Search across name, email, and groupTag fields
- `sortBy` (string, optional): Field to sort by (default: 'createdAt')
- `sortOrder` ('asc' | 'desc', optional): Sort direction (default: 'desc')

**Dynamic Filters:**
Any additional query parameters will be treated as filters. The system automatically handles different data types:
- Boolean fields: `?isVerified=true`
- Numeric fields: `?role=admin`
- Date ranges: `?createdAtFrom=2024-01-01&createdAtTo=2024-12-31`
- Multiple values: `?role=admin,super_admin` (comma-separated)
- String fields: Uses case-insensitive regex matching

**Example Requests:**
```bash
# Get all users (paginated)
GET /admin/users

# Search for users
GET /admin/users?search=john

# Filter by role
GET /admin/users?role=admin

# Filter by multiple criteria
GET /admin/users?isVerified=true&isBlocked=false&subscription=null

# Complex query with pagination and sorting
GET /admin/users?page=2&limit=20&sortBy=email&sortOrder=asc&isVerified=true

# Date range filtering
GET /admin/users?createdAtFrom=2024-01-01&createdAtTo=2024-03-31
```

**Response Format:**
```json
{
  "data": [...], // Array of user documents
  "total": 100,
  "page": 1,
  "limit": 10,
  "totalPages": 10
}
```

#### User Analytics
- **GET** `/admin/users/analytics`
  - Returns detailed user analytics and statistics

**Response Format:**
```json
{
  "statusCode": 200,
  "data": {
    "totalUsers": 1000,
    "verifiedUsers": 800,
    "blockedUsers": 50,
    "deletedUsers": 10,
    "activeSubscriptions": 300,
    "usersByRole": {
      "user": 900,
      "admin": 90,
      "super_admin": 10
    },
    "usersByLanguage": {
      "EN": 700,
      "HB": 300
    },
    "recentUsers": 150,
    "verificationRate": "80.00",
    "subscriptionRate": "30.00"
  }
}
```

## Error Handling
All endpoints return consistent error responses:

```json
{
  "statusCode": 400,
  "message": "Error description",
  "error": "Detailed error message"
}
```

## Future Enhancements
- Authentication and authorization middleware
- Additional admin modules (payments, subscriptions, etc.)
- Advanced filtering capabilities
- Export functionality
- Audit logging
- Rate limiting

## Development Notes
- The filtering system is completely dynamic and will work with any fields in the User schema
- Pagination is implemented efficiently using MongoDB skip and limit
- All operations include proper logging for debugging
- The system is designed to be easily extensible for additional admin modules