# Admin User Management API Documentation

## Overview
The Admin User Management API provides comprehensive tools for administrators to manage all user accounts, roles, permissions, and account statuses. All endpoints require admin-level authentication.

**Base URL:** `/admin/users`

**Authentication:** Admin role required (JWT with admin role)

**Authorization Header:** `Authorization: Bearer YOUR_ADMIN_JWT_TOKEN`

---

## Table of Contents
1. [List Users](#1-list-users)
2. [Get User Details](#2-get-user-details)
3. [Create User](#3-create-user)
4. [Update User](#4-update-user)
5. [Delete User](#5-delete-user)
6. [Change User Role](#6-change-user-role)
7. [Verify Owner](#7-verify-owner)
8. [Update Account Status](#8-update-account-status)
9. [Verify User Email](#9-verify-user-email)
10. [Reset User Password](#10-reset-user-password)
11. [Get User Statistics](#11-get-user-statistics)

---

## 1. List Users

Get a paginated list of all users with optional filters.

**Endpoint:** `GET /admin/users`

**Authentication:** Admin required

**Rate Limit:** 100 requests per hour

### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| page | integer | No | Page number (default: 1) |
| per_page | integer | No | Items per page (default: 20, max: 100) |
| role | string | No | Filter by role: customer, owner, admin |
| is_active | boolean | No | Filter by active status: true, false |
| is_verified | boolean | No | Filter by owner verification: true, false |
| search | string | No | Search by name, email, or username |

### Request Examples

**Get all users (page 1)**
```bash
curl -X GET "http://localhost:5000/admin/users" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

**Get owners only**
```bash
curl -X GET "http://localhost:5000/admin/users?role=owner&page=1&per_page=50" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

**Search for users**
```bash
curl -X GET "http://localhost:5000/admin/users?search=john" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

**Get inactive users**
```bash
curl -X GET "http://localhost:5000/admin/users?is_active=false" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

**Get verified owners**
```bash
curl -X GET "http://localhost:5000/admin/users?role=owner&is_verified=true" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Users retrieved successfully",
  "data": {
    "users": [
      {
        "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
        "first_name": "John",
        "last_name": "Doe",
        "username": "johndoe",
        "email": "john.doe@example.com",
        "phone_number": "+1234567890",
        "date_of_birth": "1990-05-15",
        "address": "123 Main St",
        "city": "New York",
        "country": "USA",
        "profile_image": "/static/uploads/profiles/a1b2c3d4.jpg",
        "role": "customer",
        "is_email_verified": true,
        "is_active": true,
        "is_verified": false,
        "created_at": "2024-01-15T10:30:00",
        "updated_at": "2024-01-20T14:45:00"
      },
      {
        "id": "b2c3d4e5-f6g7-8901-bcde-fg2345678901",
        "first_name": "Jane",
        "last_name": "Smith",
        "username": "janesmith",
        "email": "jane.smith@example.com",
        "phone_number": "+1987654321",
        "date_of_birth": "1985-08-22",
        "address": "456 Oak Ave",
        "city": "Los Angeles",
        "country": "USA",
        "profile_image": null,
        "role": "owner",
        "is_email_verified": true,
        "is_active": true,
        "is_verified": true,
        "created_at": "2024-01-10T09:15:00",
        "updated_at": "2024-01-18T16:20:00"
      }
    ],
    "total": 156,
    "page": 1,
    "per_page": 20,
    "pages": 8
  }
}
```

### Error Responses

**400 Bad Request** - Invalid role
```json
{
  "success": false,
  "message": "Invalid role: superuser",
  "data": null
}
```

**403 Forbidden** - Not admin
```json
{
  "success": false,
  "message": "Insufficient permissions. Required role(s): admin",
  "data": null
}
```

---

## 2. Get User Details

Get full details of a specific user by ID.

**Endpoint:** `GET /admin/users/{user_id}`

**Authentication:** Admin required

**Rate Limit:** 100 requests per hour

### Request

```bash
curl -X GET "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "User retrieved successfully",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "email": "john.doe@example.com",
    "phone_number": "+1234567890",
    "date_of_birth": "1990-05-15",
    "address": "123 Main St",
    "city": "New York",
    "country": "USA",
    "profile_image": "/static/uploads/profiles/a1b2c3d4.jpg",
    "role": "customer",
    "is_email_verified": true,
    "is_active": true,
    "is_verified": false,
    "created_at": "2024-01-15T10:30:00",
    "updated_at": "2024-01-20T14:45:00"
  }
}
```

### Error Responses

**404 Not Found**
```json
{
  "success": false,
  "message": "User not found",
  "data": null
}
```

**403 Forbidden**
```json
{
  "success": false,
  "message": "Insufficient permissions. Required role(s): admin",
  "data": null
}
```

---

## 3. Create User

Admin creates a new user account. Can optionally bypass email verification.

**Endpoint:** `POST /admin/users`

**Authentication:** Admin required

**Rate Limit:** 20 requests per hour

### Required Fields
- `first_name` (string, 2-50 characters)
- `last_name` (string, 2-50 characters)
- `username` (string, 3-50 characters, unique)
- `email` (string, valid email format, unique)
- `password` (string, min 8 chars, must include uppercase, lowercase, number, special char)

### Optional Fields
- `role` (string: customer, owner, admin - default: customer)
- `phone_number` (string, unique)
- `address` (string)
- `city` (string)
- `country` (string)
- `date_of_birth` (string, ISO format: YYYY-MM-DD)
- `bypass_email_verification` (boolean, default: false)

### Request

```bash
curl -X POST "http://localhost:5000/admin/users" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Alice",
    "last_name": "Johnson",
    "username": "alicejohnson",
    "email": "alice.johnson@example.com",
    "password": "SecurePass123!",
    "role": "owner",
    "phone_number": "+1555123456",
    "city": "Chicago",
    "country": "USA",
    "bypass_email_verification": true
  }'
```

### Minimal Request (Required Fields Only)

```bash
curl -X POST "http://localhost:5000/admin/users" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Bob",
    "last_name": "Williams",
    "username": "bobwilliams",
    "email": "bob.williams@example.com",
    "password": "Password123!"
  }'
```

### Success Response (201 Created)

```json
{
  "success": true,
  "message": "User created successfully",
  "data": {
    "id": "c3d4e5f6-g7h8-9012-cdef-gh3456789012",
    "first_name": "Alice",
    "last_name": "Johnson",
    "username": "alicejohnson",
    "email": "alice.johnson@example.com",
    "phone_number": "+1555123456",
    "date_of_birth": null,
    "address": null,
    "city": "Chicago",
    "country": "USA",
    "profile_image": null,
    "role": "owner",
    "is_email_verified": true,
    "is_active": true,
    "is_verified": false,
    "created_at": "2024-01-21T11:30:00",
    "updated_at": "2024-01-21T11:30:00"
  }
}
```

### Error Responses

**400 Bad Request** - Missing fields
```json
{
  "success": false,
  "message": "Missing required fields: email, password",
  "data": null
}
```

**400 Bad Request** - Email already exists
```json
{
  "success": false,
  "message": "Email already registered",
  "data": null
}
```

**400 Bad Request** - Username already exists
```json
{
  "success": false,
  "message": "Username already taken",
  "data": null
}
```

**400 Bad Request** - Invalid role
```json
{
  "success": false,
  "message": "Invalid role: superadmin",
  "data": null
}
```

---

## 4. Update User

Admin updates any user's information. Use dedicated endpoints for role changes, status changes, etc.

**Endpoint:** `PUT /admin/users/{user_id}`

**Authentication:** Admin required

**Rate Limit:** 50 requests per hour

### Allowed Fields
- `first_name`
- `last_name`
- `email` (must be unique)
- `username` (must be unique)
- `phone_number` (must be unique)
- `date_of_birth`
- `address`
- `city`
- `country`

**Note:** Use dedicated endpoints for changing role, status, verification, etc.

### Request

```bash
curl -X PUT "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Doe-Smith",
    "email": "john.doesmith@example.com",
    "city": "Boston",
    "country": "USA"
  }'
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "User updated successfully",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "first_name": "John",
    "last_name": "Doe-Smith",
    "username": "johndoe",
    "email": "john.doesmith@example.com",
    "phone_number": "+1234567890",
    "date_of_birth": "1990-05-15",
    "address": "123 Main St",
    "city": "Boston",
    "country": "USA",
    "profile_image": "/static/uploads/profiles/a1b2c3d4.jpg",
    "role": "customer",
    "is_email_verified": true,
    "is_active": true,
    "is_verified": false,
    "created_at": "2024-01-15T10:30:00",
    "updated_at": "2024-01-21T12:00:00"
  }
}
```

### Error Responses

**400 Bad Request** - No data
```json
{
  "success": false,
  "message": "No data provided",
  "data": null
}
```

**400 Bad Request** - No valid fields
```json
{
  "success": false,
  "message": "No valid fields provided for update",
  "data": null
}
```

**400 Bad Request** - Email already in use
```json
{
  "success": false,
  "message": "Email already in use",
  "data": null
}
```

---

## 5. Delete User

Delete a user account. Supports both soft delete (default) and hard delete.

**Endpoint:** `DELETE /admin/users/{user_id}`

**Authentication:** Admin required

**Rate Limit:** 20 requests per hour

### Query Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| hard_delete | boolean | false | If true, permanently delete from database |

**Soft Delete:** Sets `is_active=False`, data is retained  
**Hard Delete:** Permanently removes from database

### Request - Soft Delete (Default)

```bash
curl -X DELETE "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Request - Hard Delete

```bash
curl -X DELETE "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890?hard_delete=true" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK) - Soft Delete

```json
{
  "success": true,
  "message": "User deactivated successfully",
  "data": null
}
```

### Success Response (200 OK) - Hard Delete

```json
{
  "success": true,
  "message": "User permanently deleted",
  "data": null
}
```

### Error Responses

**404 Not Found**
```json
{
  "success": false,
  "message": "User not found",
  "data": null
}
```

---

## 6. Change User Role

Change a user's role (customer, owner, admin).

**Endpoint:** `PUT /admin/users/{user_id}/role`

**Authentication:** Admin required

**Rate Limit:** 20 requests per hour

### Valid Roles
- `customer` - Regular user, can browse listings
- `owner` - Can create and manage property listings
- `admin` - Full system access

### Request

```bash
curl -X PUT "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890/role" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "role": "owner"
  }'
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "User role changed from customer to owner",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "email": "john.doe@example.com",
    "phone_number": "+1234567890",
    "date_of_birth": "1990-05-15",
    "address": "123 Main St",
    "city": "New York",
    "country": "USA",
    "profile_image": "/static/uploads/profiles/a1b2c3d4.jpg",
    "role": "owner",
    "is_email_verified": true,
    "is_active": true,
    "is_verified": false,
    "created_at": "2024-01-15T10:30:00",
    "updated_at": "2024-01-21T13:00:00"
  }
}
```

### Error Responses

**400 Bad Request** - Missing role
```json
{
  "success": false,
  "message": "Missing required fields: role",
  "data": null
}
```

**400 Bad Request** - Invalid role
```json
{
  "success": false,
  "message": "Invalid role: superadmin",
  "data": null
}
```

---

## 7. Verify Owner

Manually verify an owner account. Sets `is_verified=True`.

**Endpoint:** `PUT /admin/users/{user_id}/verify`

**Authentication:** Admin required

**Rate Limit:** 50 requests per hour

**Note:** Only applicable to users with 'owner' role.

### Request

```bash
curl -X PUT "http://localhost:5000/admin/users/b2c3d4e5-f6g7-8901-bcde-fg2345678901/verify" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Owner verified successfully",
  "data": {
    "id": "b2c3d4e5-f6g7-8901-bcde-fg2345678901",
    "first_name": "Jane",
    "last_name": "Smith",
    "username": "janesmith",
    "email": "jane.smith@example.com",
    "phone_number": "+1987654321",
    "date_of_birth": "1985-08-22",
    "address": "456 Oak Ave",
    "city": "Los Angeles",
    "country": "USA",
    "profile_image": null,
    "role": "owner",
    "is_email_verified": true,
    "is_active": true,
    "is_verified": true,
    "created_at": "2024-01-10T09:15:00",
    "updated_at": "2024-01-21T14:00:00"
  }
}
```

### Error Responses

**400 Bad Request** - Not an owner
```json
{
  "success": false,
  "message": "User is not an owner",
  "data": null
}
```

**400 Bad Request** - Already verified
```json
{
  "success": false,
  "message": "Owner is already verified",
  "data": null
}
```

---

## 8. Update Account Status

Activate or deactivate a user account.

**Endpoint:** `PUT /admin/users/{user_id}/status`

**Authentication:** Admin required

**Rate Limit:** 50 requests per hour

### Request - Activate Account

```bash
curl -X PUT "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890/status" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "is_active": true
  }'
```

### Request - Deactivate Account

```bash
curl -X PUT "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890/status" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "is_active": false
  }'
```

### Success Response (200 OK) - Activated

```json
{
  "success": true,
  "message": "Account activated successfully",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "email": "john.doe@example.com",
    "role": "customer",
    "is_email_verified": true,
    "is_active": true,
    "is_verified": false,
    "created_at": "2024-01-15T10:30:00",
    "updated_at": "2024-01-21T15:00:00"
  }
}
```

### Error Responses

**400 Bad Request** - Missing field
```json
{
  "success": false,
  "message": "Missing required fields: is_active",
  "data": null
}
```

**400 Bad Request** - Invalid type
```json
{
  "success": false,
  "message": "is_active must be a boolean",
  "data": null
}
```

---

## 9. Verify User Email

Manually mark a user's email as verified. Used for customer support cases.

**Endpoint:** `PUT /admin/users/{user_id}/verify-email`

**Authentication:** Admin required

**Rate Limit:** 50 requests per hour

### Request

```bash
curl -X PUT "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890/verify-email" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Email verified successfully",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "email": "john.doe@example.com",
    "role": "customer",
    "is_email_verified": true,
    "is_active": true,
    "is_verified": false,
    "created_at": "2024-01-15T10:30:00",
    "updated_at": "2024-01-21T16:00:00"
  }
}
```

### Error Responses

**400 Bad Request** - Already verified
```json
{
  "success": false,
  "message": "Email is already verified",
  "data": null
}
```

---

## 10. Reset User Password

Admin resets a user's password. Generates a random temporary password and sends it via email.

**Endpoint:** `POST /admin/users/{user_id}/reset-password`

**Authentication:** Admin required

**Rate Limit:** 10 requests per hour

**Process:**
1. Generates secure 12-character temporary password
2. Updates user's password in database
3. Sends email to user with temporary password
4. Logs the action with admin ID

### Request

```bash
curl -X POST "http://localhost:5000/admin/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890/reset-password" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Password reset successfully. User will receive an email with temporary password.",
  "data": null
}
```

### Email Sent to User

```
Subject: Your Password Has Been Reset

Hello John,

Your password has been reset by an administrator.

Your temporary password is: Xy9#mK2$pL4@

For security reasons, please:
1. Log in using this temporary password
2. Change your password immediately after logging in

If you did not request this password reset, please contact support immediately.

Best regards,
AFFIX WEB ADVERTS Team
```

### Error Responses

**400 Bad Request** - Email failed
```json
{
  "success": false,
  "message": "Password was reset but failed to send email notification",
  "data": null
}
```

**404 Not Found**
```json
{
  "success": false,
  "message": "User not found",
  "data": null
}
```

---

## 11. Get User Statistics

Get comprehensive user statistics and analytics.

**Endpoint:** `GET /admin/users/stats`

**Authentication:** Admin required

**Rate Limit:** 100 requests per hour

### Request

```bash
curl -X GET "http://localhost:5000/admin/users/stats" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "User statistics retrieved successfully",
  "data": {
    "total_users": 1245,
    "active_users": 1198,
    "inactive_users": 47,
    "customers": 980,
    "owners": 245,
    "admins": 20,
    "verified_owners": 189,
    "email_verified": 1150,
    "recent_registrations_7days": 34
  }
}
```

### Statistics Breakdown

| Field | Description |
|-------|-------------|
| total_users | Total registered users |
| active_users | Users with is_active=True |
| inactive_users | Users with is_active=False |
| customers | Users with customer role |
| owners | Users with owner role |
| admins | Users with admin role |
| verified_owners | Owners with is_verified=True |
| email_verified | Users with is_email_verified=True |
| recent_registrations_7days | New users registered in last 7 days |

---

## Common Error Codes

| Status Code | Description |
|-------------|-------------|
| 200 | Success |
| 201 | Created |
| 400 | Bad Request - Invalid input or validation error |
| 401 | Unauthorized - Missing or invalid JWT token |
| 403 | Forbidden - Not admin or insufficient permissions |
| 404 | Not Found - Resource doesn't exist |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error |

---

## Rate Limit Headers

All responses include rate limit information:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642857600
```

---

## Security Best Practices

### For Admin Panel Developers

1. **Token Management**
   - Store admin tokens with highest security
   - Implement automatic logout after inactivity
   - Require re-authentication for sensitive operations

2. **Audit Logging**
   - Log all admin actions client-side
   - Display action history to admins
   - Track who performed password resets, role changes, etc.

3. **Confirmation Dialogs**
   - Always confirm destructive actions (hard delete)
   - Show impact warnings (e.g., "This will delete X properties")
   - Implement multi-step confirmations for critical operations

4. **Data Validation**
   - Validate all inputs before sending to API
   - Match server-side validation rules
   - Provide clear error messages

5. **Access Control**
   - Verify admin role before rendering admin UI
   - Hide admin features from non-admin users
   - Handle 403 errors gracefully

### Example: Safe User Deletion

```javascript
async function deleteUser(userId, hardDelete = false) {
  // Confirm action
  const confirmMessage = hardDelete 
    ? 'Are you sure you want to PERMANENTLY delete this user? This cannot be undone!'
    : 'Are you sure you want to deactivate this user?';
  
  if (!confirm(confirmMessage)) {
    return;
  }

  // Additional confirmation for hard delete
  if (hardDelete) {
    const finalConfirm = prompt('Type "DELETE" to confirm permanent deletion:');
    if (finalConfirm !== 'DELETE') {
      return;
    }
  }

  try {
    const url = hardDelete 
      ? `http://localhost:5000/admin/users/${userId}?hard_delete=true`
      : `http://localhost:5000/admin/users/${userId}`;

    const response = await fetch(url, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json'
      }
    });

    const data = await response.json();

    if (data.success) {
      // Log action
      logAdminAction('delete_user', { userId, hardDelete });
      
      // Update UI
      alert(data.message);
      refreshUserList();
    } else {
      alert(`Error: ${data.message}`);
    }

  } catch (error) {
    console.error('Error deleting user:', error);
    alert('Network error occurred');
  }
}
```

---

## Testing Workflow

### 1. Setup Admin Account
```bash
# Login as admin to get token
curl -X POST http://localhost:5000/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@affixwebadverts.com",
    "password": "AdminPass123!"
  }'

# Copy access_token from response
```

### 2. Test User Management Flow

```bash
# 1. Get user statistics
curl -X GET http://localhost:5000/admin/users/stats \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"

# 2. List all users
curl -X GET http://localhost:5000/admin/users \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"

# 3. Create a new user
curl -X POST http://localhost:5000/admin/users \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Test",
    "last_name": "User",
    "username": "testuser",
    "email": "test@example.com",
    "password": "TestPass123!"
  }'

# 4. Update user role to owner
curl -X PUT http://localhost:5000/admin/users/USER_ID/role \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"role": "owner"}'

# 5. Verify the owner
curl -X PUT http://localhost:5000/admin/users/USER_ID/verify \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"

# 6. Get updated statistics
curl -X GET http://localhost:5000/admin/users/stats \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```

---

## Integration Guide

### React Example: Admin User List Component

```javascript
import React, { useState, useEffect } from 'react';

function AdminUserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    page: 1,
    per_page: 20,
    role: '',
    search: ''
  });

  useEffect(() => {
    fetchUsers();
  }, [filters]);

  async function fetchUsers() {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams(
        Object.entries(filters).filter(([_, v]) => v !== '')
      );

      const response = await fetch(
        `http://localhost:5000/admin/users?${queryParams}`,
        {
          headers: {
            'Authorization': `Bearer ${getAdminToken()}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const data = await response.json();
      
      if (data.success) {
        setUsers(data.data.users);
      } else {
        console.error(data.message);
      }
    } catch (error) {
      console.error('Error fetching users:', error);
    } finally {
      setLoading(false);
    }
  }

  async function changeUserRole(userId, newRole) {
    try {
      const response = await fetch(
        `http://localhost:5000/admin/users/${userId}/role`,
        {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${getAdminToken()}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ role: newRole })
        }
      );

      const data = await response.json();
      
      if (data.success) {
        alert('Role updated successfully');
        fetchUsers(); // Refresh list
      } else {
        alert(`Error: ${data.message}`);
      }
    } catch (error) {
      console.error('Error changing role:', error);
    }
  }

  return (
    <div>
      <h2>User Management</h2>
      
      {/* Filters */}
      <div>
        <input
          type="text"
          placeholder="Search users..."
          value={filters.search}
          onChange={(e) => setFilters({...filters, search: e.target.value})}
        />
        
        <select
          value={filters.role}
          onChange={(e) => setFilters({...filters, role: e.target.value})}
        >
          <option value="">All Roles</option>
          <option value="customer">Customers</option>
          <option value="owner">Owners</option>
          <option value="admin">Admins</option>
        </select>
      </div>

      {/* User List */}
      {loading ? (
        <p>Loading...</p>
      ) : (
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {users.map(user => (
              <tr key={user.id}>
                <td>{user.first_name} {user.last_name}</td>
                <td>{user.email}</td>
                <td>{user.role}</td>
                <td>{user.is_active ? 'Active' : 'Inactive'}</td>
                <td>
                  <button onClick={() => changeUserRole(user.id, 'owner')}>
                    Make Owner
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}

function getAdminToken() {
  // Retrieve admin token from secure storage
  return localStorage.getItem('admin_token');
}

export default AdminUserList;
```

---

## Support & Documentation

**Backend Team Contact:** backend@affixwebadverts.com

**Documentation Repository:** [Link to docs repo]

**Issue Tracking:** [Link to issue tracker]

**Change Log:** Track API changes and deprecations

---

## Appendix: Complete Workflow Examples

### Example 1: Onboard New Owner

```bash
# Step 1: Create owner account
curl -X POST http://localhost:5000/admin/users \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Sarah",
    "last_name": "Parker",
    "username": "sarahparker",
    "email": "sarah.parker@example.com",
    "password": "TempPass123!",
    "role": "owner",
    "bypass_email_verification": true
  }'

# Step 2: Verify owner
curl -X PUT http://localhost:5000/admin/users/$USER_ID/verify \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# Step 3: Send password reset email
curl -X POST http://localhost:5000/admin/users/$USER_ID/reset-password \
  -H "Authorization: Bearer $ADMIN_TOKEN"
```

### Example 2: Handle Support Request - Activate Deactivated Account

```bash
# Step 1: Find user
curl -X GET "http://localhost:5000/admin/users?search=john.doe@example.com" \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# Step 2: Activate account
curl -X PUT http://localhost:5000/admin/users/$USER_ID/status \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"is_active": true}'

# Step 3: Reset password (if needed)
curl -X POST http://localhost:5000/admin/users/$USER_ID/reset-password \
  -H "Authorization: Bearer $ADMIN_TOKEN"
```

### Example 3: Audit User Base

```bash
# Get overall statistics
curl -X GET http://localhost:5000/admin/users/stats \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# Get unverified owners
curl -X GET "http://localhost:5000/admin/users?role=owner&is_verified=false" \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# Get inactive accounts
curl -X GET "http://localhost:5000/admin/users?is_active=false" \
  -H "Authorization: Bearer $ADMIN_TOKEN"
```