# Self-Registration Testing Guide

## Overview
Self-registration uses the **same validation system** as admin registration. All 4 validation requirements (Blur Detection, Lighting Validation, Quality Score, Embedding Similarity) are applied when users register themselves.

## How to Test Self-Registration

### Method 1: Generate Registration Token via API (Recommended)

1. **Start both servers:**
   ```powershell
   # Terminal 1: Backend
   .\start_backend.ps1
   
   # Terminal 2: Frontend
   .\start_frontend.ps1
   ```

2. **Login as admin** (automatic on localhost):
   - Navigate to `http://localhost:3000`
   - You should be automatically logged in as admin

3. **Generate a registration token:**
   - Open browser DevTools (F12) → Console
   - Run this JavaScript to generate a token for a test user:
   ```javascript
   // Replace 'YOUR_PID' with an actual user PID from your database
   const pid = 'YOUR_PID'; // e.g., '332', '1001', etc.
   
   fetch('http://localhost:5001/admin/generate-token', {
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
       'x-access-token': document.cookie.split('token=')[1]?.split(';')[0] || localStorage.getItem('token')
     }
   })
   .then(r => r.json())
   .then(data => {
     console.log('Registration Link:', data.link);
     // Copy the link and open it in a new tab
     window.open(data.link, '_blank');
   });
   ```

4. **Open the registration link:**
   - The link will look like: `http://localhost:3000/self-register?code=XXXXX`
   - Open it in a new tab/window (or use incognito mode to simulate a different user)

5. **Complete the registration:**
   - Follow the on-screen instructions
   - Capture 50 photos from different angles
   - Submit for validation
   - **The validation modal will appear** showing all 4 requirements, just like in admin registration

### Method 2: Direct Database Token Creation (Advanced)

If you need to create a token directly in the database:

```sql
-- Connect to your MySQL database
USE fran;

-- Insert a test token (replace PID and adjust expiry as needed)
INSERT INTO registration_tokens (code, pid, team, expires_at, created_at)
VALUES (
  'test-code-123',  -- Your test code
  '332',            -- User PID
  NULL,             -- Team GID (optional)
  DATE_ADD(NOW(), INTERVAL 1 HOUR),  -- Expires in 1 hour
  NOW()
);
```

Then access: `http://localhost:3000/self-register?code=test-code-123`

### Method 3: Using Postman/API Client

1. **Get your admin token:**
   - Login via browser and copy the token from cookies/localStorage

2. **Generate token:**
   ```
   POST http://localhost:5001/admin/generate-token
   Headers:
     x-access-token: YOUR_ADMIN_TOKEN
   ```

3. **Use the returned link:**
   - The response will contain: `{"success": true, "link": "http://localhost:3000/self-register?code=XXXXX"}`

## What to Expect During Testing

### Validation Flow:
1. **User enters registration code** → System verifies code and loads user info
2. **User captures 50 photos** → Real-time feedback on face position, lighting, etc.
3. **User clicks "Submit"** → All 50 images are sent to `/register` endpoint
4. **Backend validates all images** → Checks all 4 requirements:
   - ✅ Blur Detection (threshold: ≥80)
   - ✅ Lighting Validation (face brightness: 60-200, etc.)
   - ✅ Quality Score (minimum: 0.4 per image, 0.6 average)
   - ✅ Embedding Similarity (≥0.6, or N/A if InsightFace unavailable)
5. **Validation modal appears** → Shows detailed results for all 4 requirements
6. **Success or Failure** → User can review which images passed/failed each validation

### Validation Modal Features:
- **Overall Status**: Shows passed/total requirements
- **Per-Requirement Details**:
  - Status (PASS/FAIL/N/A)
  - Summary metrics (average scores, passed images count)
  - Threshold information
  - **Failed Images Grid**: Only shows images that failed that specific validation
  - Click any failed image to view full-size
- **Action Buttons**:
  - "Done" (green) for successful registration
  - "Try Again" (red) for failed registration

## Differences from Admin Registration

| Feature | Admin Registration | Self-Registration |
|---------|-------------------|-------------------|
| **Route** | `/face-registration` | `/self-register?code=XXX` |
| **Authentication** | Requires admin login | Requires valid registration code |
| **User Selection** | Admin selects user from dropdown | User info loaded from code |
| **Validation** | ✅ Same 4 requirements | ✅ Same 4 requirements |
| **Validation Modal** | ✅ Shows all 4 requirements | ✅ Shows all 4 requirements |
| **Failed Images Display** | ✅ Per validation | ✅ Per validation |

## Troubleshooting

### "Invalid or expired registration code"
- Token may have expired (default: 5 minutes)
- Generate a new token
- Check database: `SELECT * FROM registration_tokens WHERE code = 'YOUR_CODE';`

### "Could not retrieve information for User ID"
- The PID in the token doesn't exist in the staff database
- Verify the PID exists: Check your `staff` table or use a known PID

### Validation modal not appearing
- Check browser console for errors
- Verify `validation_results` is in the response (check Network tab)
- Ensure both frontend and backend are running on correct ports (3000 and 5001)

### Images not showing in validation modal
- Check that `validationImages` ref is populated
- Verify images are base64 encoded correctly
- Check browser console for image loading errors

## Quick Test Checklist

- [ ] Backend server running on `http://localhost:5001`
- [ ] Frontend server running on `http://localhost:3000`
- [ ] Admin logged in (automatic on localhost)
- [ ] Generated registration token for a test user
- [ ] Opened registration link in new tab/window
- [ ] Verified code and loaded user info
- [ ] Captured 50 photos
- [ ] Submitted for validation
- [ ] **Validation modal appeared with all 4 requirements**
- [ ] Can see failed images per validation requirement
- [ ] Can click failed images to view full-size
- [ ] Form resets after closing modal (for failed registrations)

## Notes

- **Same validation logic**: Self-registration uses the exact same `/register` endpoint and validation logic as admin registration
- **Code expiration**: Registration codes expire after 5 minutes by default (configurable via `REGISTRATION_TOKEN_EXPIRY_MINUTES` env var)
- **One code per user**: If a user already has a code, generating a new one will update the existing record
- **Token not deleted on verify**: The code is verified but not deleted until registration is complete (success or failure)

