# Admin Panel Implementation - Project Plan

## Project Charter

**Project Name:** H2H Admin Panel Enhancement
**Version:** 1.0
**Date:** January 11, 2026
**Project Manager:** [TBD]

### Executive Summary

This project plan outlines the implementation of a comprehensive Admin Panel for the H2H betting platform. The panel will provide administrators with tools for data management, activity simulation, user administration, and audit logging. The implementation leverages the existing FastAPI backend and React frontend infrastructure.

### Project Objectives

1. Enable administrators to reset/wipe database data safely
2. Provide seeding capabilities for test data generation
3. Implement toggleable activity simulation for testing and demos
4. Create comprehensive user management capabilities
5. Establish audit logging for all administrative actions

### Success Criteria

- All five core features fully functional and tested
- Admin actions logged with full traceability
- No data integrity issues during wipe/seed operations
- Simulation can run without impacting production stability
- User management operations complete within 2 seconds

---

## Current State Analysis

### Existing Infrastructure

| Component | Status | Location |
|-----------|--------|----------|
| Admin Router | Partial | `/backend/app/routers/admin.py` |
| Admin Settings Model | Complete | `/backend/app/models/admin_settings.py` |
| Frontend Admin Page | Partial | `/frontend/src/pages/Admin.tsx` |
| Admin API Client | Partial | `/frontend/src/api/admin.ts` |
| User Model (is_admin flag) | Complete | `/backend/app/models/user.py` |
| Simulation Script | Standalone | `/backend/simulate_activity.py` |
| Seed Script | Standalone | `/backend/seed_data.py` |
| Event Manager | Standalone | `/backend/manage_events.py` |

### Current Capabilities

The existing admin router provides:
- Admin settings retrieval and update
- Sport event CRUD operations
- Admin user verification middleware

### Gap Analysis

| Feature | Current State | Required State |
|---------|---------------|----------------|
| Data Wiper | None | Full implementation |
| Data Seeder | CLI script only | API-integrated |
| Simulation Toggle | CLI script only | API-controlled with background task |
| User Management | None | Full CRUD + balance adjustment |
| Audit Log | None | Full implementation |

---

## Work Breakdown Structure (WBS)

```
1.0 Admin Panel Enhancement
|
+-- 1.1 Foundation & Infrastructure
|   +-- 1.1.1 Create AdminAuditLog model
|   +-- 1.1.2 Add simulation_enabled flag to AdminSettings
|   +-- 1.1.3 Create admin schemas for new endpoints
|   +-- 1.1.4 Set up background task infrastructure for simulation
|   +-- 1.1.5 Update database initialization
|
+-- 1.2 Audit Logging System
|   +-- 1.2.1 Design audit log data model
|   +-- 1.2.2 Create audit logging utility functions
|   +-- 1.2.3 Implement audit log API endpoints
|   +-- 1.2.4 Create frontend audit log viewer component
|   +-- 1.2.5 Integrate audit logging into admin actions
|
+-- 1.3 Data Wiper Feature
|   +-- 1.3.1 Design wipe strategy (selective vs full)
|   +-- 1.3.2 Implement wipe endpoints with confirmation
|   +-- 1.3.3 Add safeguards (confirmation token, cooldown)
|   +-- 1.3.4 Create frontend wipe controls with confirmation modal
|   +-- 1.3.5 Integrate audit logging
|
+-- 1.4 Data Seeder Feature
|   +-- 1.4.1 Refactor seed_data.py into service module
|   +-- 1.4.2 Create configurable seeder options
|   +-- 1.4.3 Implement seed API endpoints
|   +-- 1.4.4 Create frontend seed controls
|   +-- 1.4.5 Integrate audit logging
|
+-- 1.5 Activity Simulation Feature
|   +-- 1.5.1 Refactor simulate_activity.py into service module
|   +-- 1.5.2 Create simulation manager with start/stop control
|   +-- 1.5.3 Implement simulation API endpoints
|   +-- 1.5.4 Create simulation status WebSocket events
|   +-- 1.5.5 Create frontend simulation toggle and status
|   +-- 1.5.6 Integrate audit logging
|
+-- 1.6 User Management Feature
|   +-- 1.6.1 Create user management schemas
|   +-- 1.6.2 Implement user list/search endpoint
|   +-- 1.6.3 Implement user detail/edit endpoint
|   +-- 1.6.4 Implement user status toggle (enable/disable)
|   +-- 1.6.5 Implement balance adjustment endpoint
|   +-- 1.6.6 Create frontend user management table
|   +-- 1.6.7 Create user edit modal
|   +-- 1.6.8 Create balance adjustment modal
|   +-- 1.6.9 Integrate audit logging
|
+-- 1.7 Frontend Integration
|   +-- 1.7.1 Redesign Admin.tsx with tabbed interface
|   +-- 1.7.2 Create AdminDataTools component (wipe/seed)
|   +-- 1.7.3 Create AdminSimulation component
|   +-- 1.7.4 Create AdminUsers component
|   +-- 1.7.5 Create AdminAuditLog component
|   +-- 1.7.6 Update admin API client
|   +-- 1.7.7 Add admin route protection
|
+-- 1.8 Testing & Documentation
|   +-- 1.8.1 Unit tests for admin services
|   +-- 1.8.2 Integration tests for admin endpoints
|   +-- 1.8.3 E2E tests for admin UI
|   +-- 1.8.4 Update API documentation
|   +-- 1.8.5 Create admin user guide
```

---

## Implementation Phases

### Phase 1: Foundation & Audit Infrastructure

**Objective:** Establish the foundational models, schemas, and audit logging system that other features depend on.

#### Tasks

| ID | Task | Dependencies | Files Affected |
|----|------|--------------|----------------|
| 1.1.1 | Create AdminAuditLog model | None | `backend/app/models/admin_audit_log.py`, `backend/app/models/__init__.py` |
| 1.1.2 | Add simulation_enabled to AdminSettings | None | `backend/app/models/admin_settings.py` |
| 1.1.3 | Create admin schemas | 1.1.1 | `backend/app/schemas/admin.py` |
| 1.2.2 | Create audit logging utility | 1.1.1 | `backend/app/services/audit_service.py` |
| 1.2.3 | Implement audit log endpoints | 1.2.2 | `backend/app/routers/admin.py` |

#### New File: `backend/app/models/admin_audit_log.py`

```python
# Model structure
class AdminAuditLog(Base):
    __tablename__ = "admin_audit_logs"

    id: int (PK)
    admin_user_id: int (FK -> users.id)
    action: str  # e.g., "DATA_WIPE", "USER_DISABLE", "SEED_DATA"
    action_category: str  # e.g., "data_management", "user_management", "simulation"
    target_type: str | None  # e.g., "user", "bet", "event"
    target_id: int | None
    details: dict (JSON)  # Additional context
    ip_address: str | None
    user_agent: str | None
    created_at: datetime
```

#### New File: `backend/app/schemas/admin.py`

```python
# Schema structure
class AuditLogEntry(BaseModel):
    id: int
    admin_user_id: int
    admin_username: str
    action: str
    action_category: str
    target_type: str | None
    target_id: int | None
    details: dict
    created_at: datetime

class AuditLogListResponse(BaseModel):
    items: list[AuditLogEntry]
    total: int
    page: int
    page_size: int

class DataWipeRequest(BaseModel):
    wipe_type: str  # "all", "bets", "events", "transactions", "users_except_admin"
    confirm_phrase: str  # Must match "CONFIRM WIPE"

class SeedDataRequest(BaseModel):
    user_count: int = 3
    event_count: int = 5
    bet_count: int = 10
    include_matched_bets: bool = True

class SimulationConfig(BaseModel):
    enabled: bool
    delay_seconds: float = 2.0
    actions_per_iteration: int = 3

class UserListResponse(BaseModel):
    items: list[UserAdmin]
    total: int
    page: int
    page_size: int

class UserAdmin(BaseModel):
    id: int
    email: str
    username: str
    display_name: str | None
    status: str
    is_admin: bool
    balance: Decimal
    escrow: Decimal
    total_bets: int
    wins: int
    losses: int
    created_at: datetime

class UserUpdateRequest(BaseModel):
    display_name: str | None
    status: str | None
    is_admin: bool | None

class BalanceAdjustmentRequest(BaseModel):
    amount: Decimal
    reason: str
```

---

### Phase 2: Data Management (Wiper & Seeder)

**Objective:** Implement safe data wipe and seed capabilities with proper safeguards.

#### Tasks

| ID | Task | Dependencies | Files Affected |
|----|------|--------------|----------------|
| 1.3.1 | Design wipe strategy | 1.1.1 | Design document |
| 1.3.2 | Implement wipe endpoints | 1.3.1, 1.2.2 | `backend/app/routers/admin.py` |
| 1.3.3 | Add safeguards | 1.3.2 | `backend/app/routers/admin.py` |
| 1.4.1 | Refactor seed_data.py | None | `backend/app/services/seeder_service.py` |
| 1.4.3 | Implement seed endpoints | 1.4.1, 1.2.2 | `backend/app/routers/admin.py` |

#### Data Wipe Strategy

| Wipe Type | Tables Affected | Preserved |
|-----------|-----------------|-----------|
| `bets` | Bet, BetProposal, SpreadBet, MatchComment | Users, Wallets (reset balances), Events |
| `events` | SportEvent, EventComment, related SpreadBets | Users, Wallets, generic Bets |
| `transactions` | Transaction | Users, Wallets (reset balances), Bets, Events |
| `users_except_admin` | User, Wallet, all related data | Admin users only |
| `all` | All data except admin users | Admin user accounts |

#### Wipe Safeguards

1. **Confirmation Phrase:** Request body must include `confirm_phrase: "CONFIRM WIPE"`
2. **Rate Limiting:** Maximum 1 wipe per 5 minutes
3. **Audit Logging:** Full details logged before wipe executes
4. **Backup Suggestion:** API response includes reminder to backup

#### New File: `backend/app/services/seeder_service.py`

```python
# Refactored from seed_data.py
class SeederService:
    async def seed_users(self, db, count: int) -> list[User]
    async def seed_events(self, db, admin_id: int, count: int) -> list[SportEvent]
    async def seed_bets(self, db, users: list, events: list, count: int) -> list[SpreadBet]
    async def seed_all(self, db, config: SeedDataRequest) -> SeedResult
```

---

### Phase 3: Activity Simulation

**Objective:** Enable real-time control of activity simulation from the admin panel.

#### Tasks

| ID | Task | Dependencies | Files Affected |
|----|------|--------------|----------------|
| 1.5.1 | Refactor simulate_activity.py | None | `backend/app/services/simulation_service.py` |
| 1.5.2 | Create simulation manager | 1.5.1 | `backend/app/services/simulation_manager.py` |
| 1.5.3 | Implement simulation endpoints | 1.5.2, 1.2.2 | `backend/app/routers/admin.py` |
| 1.5.4 | Create WebSocket events | 1.5.2 | `backend/app/routers/websocket.py` |

#### New File: `backend/app/services/simulation_service.py`

```python
# Refactored from simulate_activity.py
class SimulationService:
    async def create_random_user(self, db) -> User | None
    async def create_random_bet(self, db, users, events) -> SpreadBet | None
    async def take_random_bet(self, db, users) -> SpreadBet | None
    async def cancel_random_bet(self, db) -> SpreadBet | None
    async def add_event_comment(self, db, users, events) -> EventComment | None
    async def add_match_comment(self, db, users) -> MatchComment | None
    async def run_iteration(self, db) -> SimulationIterationResult
```

#### New File: `backend/app/services/simulation_manager.py`

```python
# Background task manager for simulation
class SimulationManager:
    _instance: SimulationManager | None = None
    _task: asyncio.Task | None = None
    _running: bool = False
    _config: SimulationConfig

    @classmethod
    def get_instance(cls) -> SimulationManager

    async def start(self, config: SimulationConfig) -> bool
    async def stop(self) -> bool
    def is_running(self) -> bool
    def get_status(self) -> SimulationStatus
```

#### Simulation API Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/admin/simulation/status` | GET | Get current simulation status |
| `/api/v1/admin/simulation/start` | POST | Start simulation with config |
| `/api/v1/admin/simulation/stop` | POST | Stop simulation |

---

### Phase 4: User Management

**Objective:** Provide comprehensive user administration capabilities.

#### Tasks

| ID | Task | Dependencies | Files Affected |
|----|------|--------------|----------------|
| 1.6.1 | Create user management schemas | 1.1.3 | `backend/app/schemas/admin.py` |
| 1.6.2 | Implement user list endpoint | 1.6.1 | `backend/app/routers/admin.py` |
| 1.6.3 | Implement user edit endpoint | 1.6.1, 1.2.2 | `backend/app/routers/admin.py` |
| 1.6.4 | Implement status toggle | 1.6.3 | `backend/app/routers/admin.py` |
| 1.6.5 | Implement balance adjustment | 1.6.3, 1.2.2 | `backend/app/routers/admin.py` |

#### User Management API Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/admin/users` | GET | List users with pagination/search |
| `/api/v1/admin/users/{user_id}` | GET | Get user details |
| `/api/v1/admin/users/{user_id}` | PATCH | Update user |
| `/api/v1/admin/users/{user_id}/status` | PATCH | Toggle user status |
| `/api/v1/admin/users/{user_id}/balance` | POST | Adjust balance |

#### Balance Adjustment Rules

1. Adjustment creates a Transaction record with type `ADMIN_ADJUSTMENT`
2. Both positive and negative adjustments allowed
3. Cannot reduce balance below escrow amount
4. Reason field is required and logged
5. Full audit trail maintained

---

### Phase 5: Frontend Implementation

**Objective:** Create a comprehensive admin UI with all features integrated.

#### Tasks

| ID | Task | Dependencies | Files Affected |
|----|------|--------------|----------------|
| 1.7.1 | Redesign Admin.tsx | None | `frontend/src/pages/Admin.tsx` |
| 1.7.2 | Create AdminDataTools | Phase 2 complete | `frontend/src/components/admin/AdminDataTools.tsx` |
| 1.7.3 | Create AdminSimulation | Phase 3 complete | `frontend/src/components/admin/AdminSimulation.tsx` |
| 1.7.4 | Create AdminUsers | Phase 4 complete | `frontend/src/components/admin/AdminUsers.tsx` |
| 1.7.5 | Create AdminAuditLog | Phase 1 complete | `frontend/src/components/admin/AdminAuditLog.tsx` |
| 1.7.6 | Update admin API client | All phases | `frontend/src/api/admin.ts` |

#### New Frontend Files

```
frontend/src/
  components/
    admin/
      AdminDataTools.tsx      # Wipe/Seed controls
      AdminSimulation.tsx     # Simulation toggle and status
      AdminUsers.tsx          # User table with actions
      AdminAuditLog.tsx       # Audit log viewer
      UserEditModal.tsx       # User edit dialog
      BalanceAdjustModal.tsx  # Balance adjustment dialog
      ConfirmWipeModal.tsx    # Wipe confirmation dialog
  types/
    admin.ts                  # Admin-specific types
```

#### Admin.tsx Tab Structure

```tsx
// Tab structure
<Tabs>
  <Tab label="Events">     // Existing functionality
  <Tab label="Users">      // User management table
  <Tab label="Data Tools"> // Wipe & Seed controls
  <Tab label="Simulation"> // Simulation toggle
  <Tab label="Audit Log">  // Activity log viewer
  <Tab label="Settings">   // Platform settings (existing)
</Tabs>
```

---

## File Changes Summary

### Backend - New Files

| File Path | Purpose |
|-----------|---------|
| `backend/app/models/admin_audit_log.py` | Audit log data model |
| `backend/app/schemas/admin.py` | All admin-related Pydantic schemas |
| `backend/app/services/audit_service.py` | Audit logging utility functions |
| `backend/app/services/seeder_service.py` | Data seeding service |
| `backend/app/services/simulation_service.py` | Simulation actions service |
| `backend/app/services/simulation_manager.py` | Background task manager |
| `backend/app/services/wiper_service.py` | Data wipe service |

### Backend - Modified Files

| File Path | Changes |
|-----------|---------|
| `backend/app/models/__init__.py` | Export AdminAuditLog |
| `backend/app/models/admin_settings.py` | Add simulation_enabled, last_wipe_at fields |
| `backend/app/routers/admin.py` | Add all new endpoints |
| `backend/app/routers/websocket.py` | Add simulation status events |
| `backend/app/main.py` | Initialize simulation manager on startup |

### Frontend - New Files

| File Path | Purpose |
|-----------|---------|
| `frontend/src/components/admin/AdminDataTools.tsx` | Wipe/Seed UI |
| `frontend/src/components/admin/AdminSimulation.tsx` | Simulation controls |
| `frontend/src/components/admin/AdminUsers.tsx` | User management table |
| `frontend/src/components/admin/AdminAuditLog.tsx` | Audit log viewer |
| `frontend/src/components/admin/UserEditModal.tsx` | User edit dialog |
| `frontend/src/components/admin/BalanceAdjustModal.tsx` | Balance adjustment |
| `frontend/src/components/admin/ConfirmWipeModal.tsx` | Wipe confirmation |
| `frontend/src/types/admin.ts` | TypeScript types |

### Frontend - Modified Files

| File Path | Changes |
|-----------|---------|
| `frontend/src/pages/Admin.tsx` | Complete redesign with tabs |
| `frontend/src/api/admin.ts` | Add all new API methods |

---

## Risk Assessment

### Risk Register

| ID | Risk Description | Probability | Impact | Score | Response Strategy | Owner |
|----|------------------|-------------|--------|-------|-------------------|-------|
| R1 | Data wipe accidentally executed on production | Low | Critical | High | Implement multi-factor confirmation, rate limiting, and distinct visual warnings for destructive operations | Backend Lead |
| R2 | Simulation causes performance degradation | Medium | Medium | Medium | Implement resource limits, configurable delays, automatic pause on high load | Backend Lead |
| R3 | Audit log table grows too large | Medium | Low | Low | Implement log rotation/archival policy, add index on created_at | DBA/Backend |
| R4 | Balance adjustment creates accounting discrepancy | Low | High | Medium | Require reason, create Transaction records, implement double-entry validation | Backend Lead |
| R5 | Admin privileges escalation | Low | Critical | High | Audit all is_admin changes, require existing admin to grant, log IP addresses | Security Lead |
| R6 | WebSocket connection issues during simulation | Medium | Low | Low | Graceful degradation - simulation continues even if status updates fail | Frontend Lead |
| R7 | Race conditions during concurrent admin operations | Low | Medium | Medium | Use database transactions with proper isolation, implement optimistic locking where needed | Backend Lead |

### Mitigation Strategies

**R1 - Accidental Data Wipe:**
- Require exact confirmation phrase: "CONFIRM WIPE"
- Show count of records to be deleted before confirmation
- 5-minute cooldown between wipes
- Distinct red/warning styling on wipe button
- Audit log entry created BEFORE wipe executes

**R2 - Simulation Performance:**
- Configurable delay between iterations (default 2 seconds)
- Maximum 5 actions per iteration
- Automatic pause if > 100 pending database connections
- CPU/memory monitoring hooks

**R5 - Admin Escalation:**
- Cannot remove own admin privileges
- Cannot create admin if no existing admin (seed only)
- Email notification on admin role changes (future enhancement)
- All admin changes logged with IP, user agent

---

## Dependencies

### Task Dependencies Graph

```
Phase 1 (Foundation)
  1.1.1 AdminAuditLog Model ─────────────────┐
                                              │
  1.1.2 AdminSettings Update                  ├──► 1.2.2 Audit Service ──► All subsequent features
                                              │
  1.1.3 Admin Schemas ───────────────────────┘

Phase 2 (Data Management) - Requires Phase 1
  1.4.1 Seeder Service ──► 1.4.3 Seed Endpoints
  1.3.2 Wipe Endpoints ──► 1.3.3 Safeguards

Phase 3 (Simulation) - Requires Phase 1
  1.5.1 Simulation Service ──► 1.5.2 Simulation Manager ──► 1.5.3 Endpoints

Phase 4 (User Management) - Requires Phase 1
  1.6.1 Schemas ──► 1.6.2-1.6.5 Endpoints

Phase 5 (Frontend) - Requires Backend Phases
  Backend Phase 1 ──► 1.7.5 AdminAuditLog Component
  Backend Phase 2 ──► 1.7.2 AdminDataTools Component
  Backend Phase 3 ──► 1.7.3 AdminSimulation Component
  Backend Phase 4 ──► 1.7.4 AdminUsers Component
  All Components ──► 1.7.1 Admin.tsx Integration
```

### External Dependencies

| Dependency | Version | Purpose | Status |
|------------|---------|---------|--------|
| FastAPI | 0.100+ | Backend framework | Existing |
| SQLAlchemy | 2.0+ | ORM with async support | Existing |
| React | 18+ | Frontend framework | Existing |
| TanStack Query | 5+ | Server state management | Existing |
| Tailwind CSS | 3+ | Styling | Existing |

---

## Acceptance Criteria

### Feature 1: Data Wiper

| Criteria | Description | Validation Method |
|----------|-------------|-------------------|
| AC1.1 | Admin can select wipe type (all, bets, events, transactions, users_except_admin) | UI/API test |
| AC1.2 | Wipe requires exact confirmation phrase "CONFIRM WIPE" | API test with incorrect phrase should fail |
| AC1.3 | Wipe shows count of affected records before confirmation | UI displays counts |
| AC1.4 | 5-minute cooldown enforced between wipes | API returns 429 within cooldown |
| AC1.5 | Wipe is logged to audit log before execution | Audit log entry exists |
| AC1.6 | User wallets reset to clean state after relevant wipes | Balance = 0, Escrow = 0 |

### Feature 2: Data Seeder

| Criteria | Description | Validation Method |
|----------|-------------|-------------------|
| AC2.1 | Admin can specify number of users, events, bets to create | API accepts parameters |
| AC2.2 | Seeded users have valid credentials (password123) | Can login as seeded user |
| AC2.3 | Seeded bets follow business rules (valid stakes, statuses) | Data validation |
| AC2.4 | Seed operation is idempotent (no duplicates on repeat) | Run twice, check counts |
| AC2.5 | Seed action logged to audit log | Audit entry with counts |

### Feature 3: Activity Simulation

| Criteria | Description | Validation Method |
|----------|-------------|-------------------|
| AC3.1 | Admin can start simulation with configurable delay | API accepts config |
| AC3.2 | Admin can stop running simulation | Status changes to stopped |
| AC3.3 | Simulation status visible in real-time | WebSocket or polling updates |
| AC3.4 | Simulation creates realistic activity (users, bets, comments) | Check new records created |
| AC3.5 | Simulation survives without active WebSocket connections | Background task continues |
| AC3.6 | Start/stop actions logged to audit log | Audit entries exist |

### Feature 4: User Management

| Criteria | Description | Validation Method |
|----------|-------------|-------------------|
| AC4.1 | Admin can view paginated list of all users | API returns paginated results |
| AC4.2 | Admin can search users by email/username | Search returns filtered results |
| AC4.3 | Admin can edit user display name | Update persists |
| AC4.4 | Admin can disable/enable user accounts | Status changes, user cannot login when disabled |
| AC4.5 | Admin can adjust user balance (positive/negative) | Balance updated, Transaction created |
| AC4.6 | Balance adjustment requires reason | API rejects empty reason |
| AC4.7 | Cannot reduce balance below current escrow | API returns validation error |
| AC4.8 | All user modifications logged | Audit entries with details |

### Feature 5: Audit Log

| Criteria | Description | Validation Method |
|----------|-------------|-------------------|
| AC5.1 | All admin actions create audit log entries | Check log after each action |
| AC5.2 | Audit log displays with pagination | API returns paginated results |
| AC5.3 | Audit log filterable by action type, date range, admin | Filters work correctly |
| AC5.4 | Audit entries include admin username, timestamp, details | All fields populated |
| AC5.5 | Audit log is append-only (entries cannot be deleted via API) | No DELETE endpoint |

---

## API Endpoint Summary

### New Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/v1/admin/audit-logs` | List audit logs with filters |
| POST | `/api/v1/admin/data/wipe` | Wipe database data |
| GET | `/api/v1/admin/data/wipe/preview` | Preview wipe (record counts) |
| POST | `/api/v1/admin/data/seed` | Seed test data |
| GET | `/api/v1/admin/simulation/status` | Get simulation status |
| POST | `/api/v1/admin/simulation/start` | Start simulation |
| POST | `/api/v1/admin/simulation/stop` | Stop simulation |
| GET | `/api/v1/admin/users` | List users |
| GET | `/api/v1/admin/users/{user_id}` | Get user details |
| PATCH | `/api/v1/admin/users/{user_id}` | Update user |
| PATCH | `/api/v1/admin/users/{user_id}/status` | Toggle user status |
| POST | `/api/v1/admin/users/{user_id}/balance` | Adjust balance |

---

## Database Schema Changes

### New Table: admin_audit_logs

```sql
CREATE TABLE admin_audit_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    admin_user_id INTEGER NOT NULL REFERENCES users(id),
    action VARCHAR(100) NOT NULL,
    action_category VARCHAR(50) NOT NULL,
    target_type VARCHAR(50),
    target_id INTEGER,
    details JSON,
    ip_address VARCHAR(45),
    user_agent VARCHAR(500),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    INDEX idx_audit_admin_user (admin_user_id),
    INDEX idx_audit_action (action),
    INDEX idx_audit_created (created_at),
    INDEX idx_audit_category (action_category)
);
```

### Modified Table: admin_settings

```sql
ALTER TABLE admin_settings ADD COLUMN simulation_enabled BOOLEAN DEFAULT FALSE;
ALTER TABLE admin_settings ADD COLUMN simulation_delay_seconds FLOAT DEFAULT 2.0;
ALTER TABLE admin_settings ADD COLUMN simulation_actions_per_iteration INTEGER DEFAULT 3;
ALTER TABLE admin_settings ADD COLUMN last_wipe_at TIMESTAMP;
```

### New Transaction Type

```python
class TransactionType(enum.Enum):
    # ... existing types ...
    ADMIN_ADJUSTMENT = "admin_adjustment"  # New type for balance adjustments
```

---

## Quality Assurance Plan

### Test Coverage Requirements

| Component | Unit Tests | Integration Tests | E2E Tests |
|-----------|------------|-------------------|-----------|
| Audit Service | 90%+ | Required | N/A |
| Wiper Service | 90%+ | Required | Required |
| Seeder Service | 80%+ | Required | Optional |
| Simulation Manager | 80%+ | Required | Optional |
| User Management Endpoints | N/A | Required | Required |
| Frontend Components | N/A | N/A | Required |

### Test Scenarios

**Data Wiper:**
1. Successful wipe with correct confirmation
2. Rejected wipe with incorrect confirmation
3. Cooldown enforcement
4. Partial wipe (bets only)
5. Full wipe preserving admin

**Simulation:**
1. Start simulation
2. Stop running simulation
3. Status updates while running
4. Restart after stop
5. Behavior with no events/users

**User Management:**
1. List with pagination
2. Search by email
3. Update user details
4. Disable active user
5. Positive balance adjustment
6. Negative balance adjustment
7. Balance adjustment below escrow (should fail)

---

## Appendix A: Audit Log Action Codes

| Action Code | Category | Description |
|-------------|----------|-------------|
| `DATA_WIPE` | data_management | Database wipe executed |
| `DATA_SEED` | data_management | Test data seeded |
| `SIMULATION_START` | simulation | Simulation started |
| `SIMULATION_STOP` | simulation | Simulation stopped |
| `USER_UPDATE` | user_management | User details modified |
| `USER_DISABLE` | user_management | User account disabled |
| `USER_ENABLE` | user_management | User account enabled |
| `USER_BALANCE_ADJUST` | user_management | Balance adjusted |
| `USER_ADMIN_GRANT` | user_management | Admin role granted |
| `USER_ADMIN_REVOKE` | user_management | Admin role revoked |
| `EVENT_CREATE` | event_management | Sport event created |
| `EVENT_UPDATE` | event_management | Sport event updated |
| `EVENT_DELETE` | event_management | Sport event deleted |
| `SETTINGS_UPDATE` | settings | Platform settings changed |

---

## Appendix B: UI Wireframes

### Admin Page - Tab Layout

```
+------------------------------------------------------------------+
|  Admin Panel                                          [Settings]  |
+------------------------------------------------------------------+
| [Events] [Users] [Data Tools] [Simulation] [Audit Log]           |
+------------------------------------------------------------------+
|                                                                   |
|  [Tab Content Area]                                               |
|                                                                   |
+------------------------------------------------------------------+
```

### Data Tools Tab

```
+------------------------------------------------------------------+
|  Data Management                                                  |
+------------------------------------------------------------------+
|                                                                   |
|  +-- Database Reset ------------------------------------------+   |
|  |                                                            |   |
|  |  [!] Warning: This will permanently delete data           |   |
|  |                                                            |   |
|  |  Wipe Type: [Dropdown: All/Bets/Events/Transactions/Users]|   |
|  |                                                            |   |
|  |  Records to delete:                                        |   |
|  |    - Bets: 145                                             |   |
|  |    - Events: 23                                            |   |
|  |    - Transactions: 892                                     |   |
|  |                                                            |   |
|  |  [Wipe Data - Requires Confirmation]                       |   |
|  +------------------------------------------------------------+   |
|                                                                   |
|  +-- Seed Test Data -----------------------------------------+   |
|  |                                                            |   |
|  |  Users to create: [__3__]                                  |   |
|  |  Events to create: [__5__]                                 |   |
|  |  Bets to create: [__10__]                                  |   |
|  |  [x] Include matched bets                                  |   |
|  |                                                            |   |
|  |  [Seed Data]                                               |   |
|  +------------------------------------------------------------+   |
+------------------------------------------------------------------+
```

### User Management Tab

```
+------------------------------------------------------------------+
|  User Management                                                  |
+------------------------------------------------------------------+
|                                                                   |
|  Search: [________________________] [Search]                      |
|                                                                   |
|  +-------+----------+-------------+--------+--------+---------+   |
|  | ID    | Username | Email       | Status | Balance| Actions |   |
|  +-------+----------+-------------+--------+--------+---------+   |
|  | 1     | alice    | alice@...   | Active | $1,000 | [Edit]  |   |
|  | 2     | bob      | bob@...     | Active | $850   | [Edit]  |   |
|  | 3     | charlie  | charlie@... | Disabled| $500  | [Edit]  |   |
|  +-------+----------+-------------+--------+--------+---------+   |
|                                                                   |
|  [< Prev] Page 1 of 5 [Next >]                                    |
+------------------------------------------------------------------+
```

---

## Revision History

| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2026-01-11 | Claude | Initial project plan |
