# Factory Reset Feature Guide

## Overview

The factory reset feature allows admins to wipe all catalog and content data (colleges, departments, courses, topics, etc.) while **preserving all user accounts, progress records, and learning history**.

Everything deleted is **soft-deleted (archived)** and can be restored at any time.

## Endpoints

### 1. Preview Factory Reset

**GET** `/api/v1/admin/system/factory-reset-preview`

Shows what will be deleted without actually deleting anything.

**Response:**
```json
{
  "success": true,
  "message": "Factory reset preview",
  "data": {
    "warning": "This will soft-delete all catalog and content items but preserve all user data",
    "itemsToArchive": {
      "colleges": 2,
      "departments": 4,
      "courses": 8,
      "topics": 32,
      "lessons": 128,
      "videos": 256,
      "notes": 150,
      "discussions": 45
    },
    "willNotDelete": [
      "Users (all preserved)",
      "User progress records",
      "Saved items",
      "Quiz attempts"
    ]
  }
}
```

### 2. Execute Factory Reset

**POST** `/api/v1/admin/system/factory-reset`

⚠️ **WARNING**: This is destructive. It archives all colleges, departments, courses, and topics.

**Request:**
```bash
curl -X POST http://127.0.0.1:4000/api/v1/admin/system/factory-reset \
  -H "Content-Type: application/json" \
  -H "Cookie: dailydew_token=<token>" \
  --data '{}'
```

**Response:**
```json
{
  "success": true,
  "message": "Factory reset completed",
  "data": {
    "message": "All catalog and content items have been archived. User data and progress preserved.",
    "itemsArchived": {
      "colleges": "archived",
      "departments": "archived",
      "courses": "archived",
      "topics": "archived"
    },
    "restored": "Use restore endpoints or contact admin to restore individual items"
  }
}
```

### 3. Restore From Factory Reset

**POST** `/api/v1/admin/system/factory-reset-restore`

Reverses a factory reset by unarchiving all catalog items.

**Request:**
```bash
curl -X POST http://127.0.0.1:4000/api/v1/admin/system/factory-reset-restore \
  -H "Content-Type: application/json" \
  -H "Cookie: dailydew_token=<token>" \
  --data '{}'
```

**Response:**
```json
{
  "success": true,
  "message": "Factory reset restoration completed",
  "data": {
    "message": "All archived catalog and content items have been restored.",
    "restored": {
      "colleges": 2,
      "departments": 4,
      "courses": 8,
      "topics": 32
    }
  }
}
```

## What Gets Deleted vs. Preserved

### ❌ Deleted (Soft / Archived)
- Colleges
- Departments
- Courses
- Topics
- Lessons
- Videos
- Notes (optional, depends on design)
- Discussions (optional, depends on design)

### ✅ Preserved
- All user accounts (STUDENT and ADMIN)
- User profile data
- TopicProgress records (which topics each student has viewed)
- LessonProgress records
- SavedItems (bookmarked items)
- QuizAttempts and scores
- Notifications
- Announcements
- Admin audit logs

## Frontend Implementation

### UI Requirements

On the Admin Integration/Settings page, add a "System" tab with:

1. **Factory Reset Preview Button** (normal styling)
   - On click: Fetch `/admin/system/factory-reset-preview`
   - Display a modal showing counts of items to be deleted
   - Example: "This will delete 32 topics, 8 courses, 4 departments, 2 colleges"

2. **VERY RED Factory Reset Button** (prominent warning styling)
   - Hidden until preview is fetched (or always visible with warning)
   - On click: Show a confirmation dialog with:
     - ⚠️ Large warning icon
     - "This will permanently delete all courses, topics, and content"
     - "User accounts and progress will be preserved"
     - Two buttons: **"CANCEL"** (default) and **"RESET EVERYTHING"** (red, destructive)
   - If confirmed: POST to `/admin/system/factory-reset`
   - Show success toast or redirect

3. **Restore Button** (secondary styling)
   - Only visible/enabled if there are archived items
   - On click: Confirm "Restore all archived items?"
   - If confirmed: POST to `/admin/system/factory-reset-restore`
   - Show success message

### Example React Component Stub

```tsx
// AdminIntegrationPage.tsx (integrations tab)

export function AdminIntegrationPage() {
  const [preview, setPreview] = useState<FactoryResetPreview | null>(null);
  const [loading, setLoading] = useState(false);
  const [showResetConfirm, setShowResetConfirm] = useState(false);

  const handlePreview = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/v1/admin/system/factory-reset-preview', {
        credentials: 'include'
      });
      const data = await res.json();
      setPreview(data.data);
    } finally {
      setLoading(false);
    }
  };

  const handleReset = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/v1/admin/system/factory-reset', {
        method: 'POST',
        credentials: 'include'
      });
      if (res.ok) {
        toast.success('Factory reset completed. All items archived.');
      } else {
        toast.error('Factory reset failed');
      }
    } finally {
      setLoading(false);
      setShowResetConfirm(false);
    }
  };

  return (
    <div className="system-tab">
      <h2>System Management</h2>

      <div className="factory-reset-section">
        <h3>⚠️ Factory Reset</h3>
        <p>Delete all courses, topics, and content while preserving user accounts.</p>

        <button onClick={handlePreview} disabled={loading}>
          Preview Reset
        </button>

        {preview && (
          <div className="preview-box">
            <p>{preview.itemsToArchive.topics} topics</p>
            <p>{preview.itemsToArchive.courses} courses</p>
            <p>{preview.itemsToArchive.departments} departments</p>
            <button
              className="btn-danger"
              onClick={() => setShowResetConfirm(true)}
              style={{ backgroundColor: '#dc2626', color: 'white' }}
            >
              🔥 RESET EVERYTHING
            </button>
          </div>
        )}

        {showResetConfirm && (
          <ConfirmDialog
            title="Factory Reset?"
            message="This will delete all courses and topics. User data will be preserved."
            onConfirm={handleReset}
            onCancel={() => setShowResetConfirm(false)}
          />
        )}
      </div>
    </div>
  );
}
```

## API Contracts

### FactoryResetPreviewResponse
```typescript
interface FactoryResetPreviewResponse {
  success: boolean;
  message: string;
  data: {
    warning: string;
    itemsToArchive: {
      colleges: number;
      departments: number;
      courses: number;
      topics: number;
      lessons: number;
      videos: number;
      notes: number;
      discussions: number;
    };
    willNotDelete: string[];
  };
}
```

### FactoryResetResponse
```typescript
interface FactoryResetResponse {
  success: boolean;
  message: string;
  data: {
    message: string;
    itemsArchived: {
      colleges: string;
      departments: string;
      courses: string;
      topics: string;
    };
    restored: string;
  };
}
```

## Security & Audit

- All factory reset operations require **admin authentication** (`requireAuth + requireAdmin`)
- Every reset is logged in `AdminAuditLog` with:
  - `action: "FACTORY_RESET"` or `"FACTORY_RESET_RESTORE"`
  - `actorId`: ID of the admin who triggered it
  - `metadata`: timestamp and description
- Admins can review audit logs to see who reset the system and when

## Future Enhancements

1. Confirmation code entry (e.g., "Type RESET to confirm")
2. Email notification to other admins before/after reset
3. Backup export before reset
4. Scheduled reset with advance warning
5. Granular reset options (reset only courses, keep colleges, etc.)
