# Firebase WPA Assessment Schema

## Collection Structure

### 1. `assessments` Collection

**Document ID**: `{assessmentId}` (e.g., "WPA_001", "DMT_WOUNDS")

**Document Fields:**
```typescript
{
  // Metadata fields (required for DMT viewer compatibility)
  assessment_id: string,          // "WPA_001"
  assessment_code: string,        // "WPA-SAFETY-001"
  total_score_items: number,      // 5
  source_file: string,           // "wpa-safety-001.json"
  
  // Assessment details (required for DMT viewer compatibility)
  description: string,            // "Workplace Safety Assessment"
  assessment_type: string,        // "practical_skills"
  norm: string,                  // "OSHA Safety Standards"
  active: boolean,               // true
  auto_activate: boolean,        // false
  number_of_retests: number,     // 3
  instruction: string,           // "Assessment instructions..."
  
  // WPA Builder specific fields
  created_by: string,            // User ID who created assessment
  created_at: timestamp,         // Creation timestamp
  last_modified: timestamp,      // Last modification timestamp
  
  // System fields
  version: string,               // "1.0" (for future migrations)
  data_source: string,          // "wpa_builder" | "dmt_import"
}
```

### 2. `assessments/{assessmentId}/criteria` Subcollection

**Document ID**: Auto-generated or `{sortCode}` (e.g., "001", "002")

**Document Fields:**
```typescript
{
  // Required fields (for DMT viewer compatibility)
  description: string,           // "Identify workplace hazards"
  weight?: number,              // 2 (optional)
  sort_code?: number,           // 1 (optional)
  
  // WPA Builder enhanced fields
  what_to_look_for: string[],   // ["Check visual scanning", "Identify hazards"]
  
  // System fields
  created_at: timestamp,
  order_index: number,          // For reliable ordering
}
```

### 3. `assessments/{assessmentId}/poi_assignments` Subcollection

**Document ID**: `{poiId}` (e.g., "training_center_01")

**Document Fields:**
```typescript
{
  poi_id: string,               // "training_center_01"
  poi_name: string,             // "Main Training Center"
  poi_type: string,             // "Training Facility"
  category: string,             // "training"
  is_required: boolean,         // true
  unlock_level?: number,        // 1 (optional)
  prerequisite?: string,        // "basic_safety" (optional)
  
  // System fields
  assigned_at: timestamp,
  assigned_by: string,          // User ID
}
```

### 4. `assessments/{assessmentId}/results` Subcollection

**Document ID**: `{userId}_{attemptId}` (e.g., "user123_001")

**Document Fields:**
```typescript
{
  // Assessment session info
  user_id: string,
  assessor_id?: string,         // Qualified assessor who conducted assessment
  attempt_number: number,       // 1, 2, 3 (for retests)
  session_id: string,          // Unique session identifier
  
  // Assessment results
  completed_at?: timestamp,     // When assessment was completed
  final_score?: number,         // 85.5 (percentage)
  passed: boolean,             // true/false
  status: string,              // "in_progress" | "completed" | "abandoned"
  
  // Detailed responses
  criteria_responses: {
    [criteriaId: string]: {
      competency: "competent" | "not_competent" | "needs_improvement",
      score?: number,
      comments?: string,
      assessor_notes?: string,
      completed_at: timestamp,
    }
  },
  
  // Overall assessment
  overall_comments?: string,
  assessor_signature?: string,
  media_attachments?: string[], // URLs to uploaded files
  
  // System fields
  started_at: timestamp,
  last_updated: timestamp,
}
```

### 5. `pois` Collection (Enhanced)

**Document ID**: `{poiId}` (e.g., "training_center_01")

**Document Fields:**
```typescript
{
  // Basic POI info
  id: string,
  name: string,
  description: string,
  type: string,
  category: string,
  
  // Map positioning
  x: number,                    // 0.1 to 1.0
  y: number,                    // 0.1 to 1.0
  
  // Assessment assignments
  assigned_assessments: string[], // ["WPA_001", "WPA_002"]
  
  // Access control
  unlock_level?: number,
  prerequisites?: string[],
  
  // System fields
  created_at: timestamp,
  updated_at: timestamp,
}
```

### 6. `users` Collection

**Document ID**: `{userId}` (Firebase Auth UID)

**Document Fields:**
```typescript
{
  // Profile info
  email: string,
  display_name: string,
  role: "student" | "assessor" | "content_developer" | "admin",
  
  // Assessment tracking
  assessments_completed: string[], // Assessment IDs
  current_level: number,
  
  // Content creation (for developers)
  assessments_created?: string[], // Assessment IDs created by this user
  
  // System fields
  created_at: timestamp,
  last_login: timestamp,
  profile_updated_at: timestamp,
}
```

## Data Transformation for DMT Viewer Compatibility

When serving data to the DMT Assessment Viewer, we'll transform the Firebase data to match the expected JSON structure:

```typescript
// Firebase to DMT JSON transformation
function transformForDMTViewer(assessmentDoc, criteriaCollection) {
  return {
    metadata: {
      assessment_id: assessmentDoc.assessment_id,
      assessment_code: assessmentDoc.assessment_code,
      total_score_items: assessmentDoc.total_score_items,
      source_file: assessmentDoc.source_file,
    },
    assessment: {
      description: assessmentDoc.description,
      assessment_type: assessmentDoc.assessment_type,
      norm: assessmentDoc.norm,
      active: assessmentDoc.active,
      auto_activate: assessmentDoc.auto_activate,
      number_of_retests: assessmentDoc.number_of_retests,
      instruction: assessmentDoc.instruction,
    },
    score_items: {
      related: criteriaCollection.docs.map(doc => ({
        description: doc.data().description,
        weight: doc.data().weight,
        sort_code: doc.data().sort_code,
        // Note: what_to_look_for is available but not needed for DMT viewer
      }))
    },
    // poi_assignments included if needed
  };
}
```

## Migration Strategy

1. **Phase 1**: Create Firebase collections and migrate existing DMT assessments
2. **Phase 2**: Connect WPA Builder to Firebase
3. **Phase 3**: Update DMT Viewer to read from Firebase with fallback to JSON files
4. **Phase 4**: Full migration complete

## Security Rules

```javascript
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Assessments - read for all authenticated users, write for content developers
    match /assessments/{assessmentId} {
      allow read: if request.auth != null;
      allow write: if request.auth != null && 
        (resource == null || resource.data.created_by == request.auth.uid ||
         get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role in ['content_developer', 'admin']);
      
      // Criteria subcollection
      match /criteria/{criteriaId} {
        allow read: if request.auth != null;
        allow write: if request.auth != null && 
          get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role in ['content_developer', 'admin'];
      }
      
      // Results subcollection
      match /results/{resultId} {
        allow read: if request.auth != null && 
          (request.auth.uid == resource.data.user_id || 
           get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role in ['assessor', 'admin']);
        allow write: if request.auth != null && 
          (request.auth.uid == resource.data.user_id || 
           get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role in ['assessor', 'admin']);
      }
    }
    
    // User profiles
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}
```

This schema ensures:
✅ **Full compatibility** with existing DMT Assessment Viewer
✅ **All WPA Builder features** preserved and enhanced
✅ **Scalable structure** for future features
✅ **Proper security** with role-based access control
✅ **Audit trail** with timestamps and user tracking 