# Fix Invalid Questions API

## 📋 Tổng quan

API để kiểm tra và fix các câu hỏi có `text = "default"` hoặc `text` empty trong `ImportQuestionEms`, sau đó update lại EMS.

---

## 🎯 Use Case

**Vấn đề:**
- ImportExamPartEms có `question_ids = [326940, 326941, 329194, 329195]`
- Một số câu trong ImportQuestionEms có `data_import.text = "default"` hoặc empty
- Cần loại bỏ các câu invalid và update lại EMS

**Giải pháp:**
- API tự động check từng câu hỏi
- Filter ra câu valid
- Update EMS baikiemtra với `maxMark` đúng
- Update EMS test với `listQuestion` chỉ chứa câu valid

---

## 📡 API Endpoint

### **POST /api/exam_part/fix-invalid-questions**

### **Input (Option 1 - Recommended):**

```json
{
  "import_exam_part_id": 123
}
```

**Description:**
- Tự động lấy `question_ids` từ `ImportExamPartEms.data_import`
- Tự động lấy `idBaiKiemTra`, `idTest`, `idTenant` từ `data_import`

### **Input (Option 2 - Manual):**

```json
{
  "question_ids": [326940, 326941, 329194, 329195]
}
```

**Note:** Nếu dùng option này, phải provide `import_exam_part_id` để update EMS

---

## 📊 Response

### **Success Response:**

```json
{
  "success": true,
  "message": "Fixed invalid questions. Updated EMS with 2 valid questions.",
  "data": {
    "total_questions": 4,
    "invalid_questions": 2,
    "valid_questions": 2,
    "invalid_ids": [326940, 329194],
    "valid_ids": [326941, 329195],
    "ems_update_results": {
      "baikiemtra": {
        "url": "https://apiems.hocmai.vn/admin/baikiemtra/20885?idTenant=7",
        "http_code": 200,
        "response": {...},
        "max_mark_updated": 2
      },
      "test": {
        "url": "https://apiems.hocmai.vn/admin/test/20485?idTenant=7",
        "http_code": 200,
        "response": {...},
        "questions_count": 2
      }
    }
  }
}
```

### **Error Response (No valid questions):**

```json
{
  "success": false,
  "message": "No valid questions found",
  "data": {
    "total_questions": 4,
    "invalid_questions": 4,
    "valid_questions": 0,
    "invalid_ids": [326940, 326941, 329194, 329195]
  }
}
```

### **Info Response (All valid):**

```json
{
  "success": true,
  "message": "All questions are valid. No update needed.",
  "data": {
    "total_questions": 4,
    "invalid_questions": 0,
    "valid_questions": 4,
    "valid_ids": [326940, 326941, 329194, 329195]
  }
}
```

---

## 🔄 Flow Diagram

```
┌─────────────────────────────────────────────────────────────┐
│  POST /api/exam_part/fix-invalid-questions                  │
│  Body: { import_exam_part_id: 123 }                         │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  Step 1: Get question_ids from ImportExamPartEms            │
│  - data_import.question_ids = [326940, 326941, ...]         │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  Step 2: Check each question in ImportQuestionEms           │
│                                                              │
│  Question 326940:                                            │
│  - data_import.text = "default" → ❌ INVALID               │
│                                                              │
│  Question 326941:                                            │
│  - data_import.text = "What is...?" → ✅ VALID             │
│                                                              │
│  Question 329194:                                            │
│  - data_import.text = "" (empty) → ❌ INVALID              │
│                                                              │
│  Question 329195:                                            │
│  - data_import.text = "Choose the..." → ✅ VALID           │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  Step 3: Filter results                                      │
│  - Invalid: [326940, 329194]                                │
│  - Valid: [326941, 329195]                                  │
│  - maxMark: 2                                               │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  Step 4: Login to EMS                                        │
│  POST https://apiems.hocmai.vn/admin/user/login             │
│  → Get token                                                 │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  Step 5: Update baikiemtra                                   │
│  PUT https://apiems.hocmai.vn/admin/baikiemtra/20885?       │
│      idTenant=7                                              │
│                                                              │
│  Body: {                                                     │
│    "maxMark": 2,        ← Updated (was 4, now 2)           │
│    "name": "...",                                           │
│    "listClass": [...],                                      │
│    ...                                                       │
│  }                                                           │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  Step 6: Update test                                         │
│  PUT https://apiems.hocmai.vn/admin/test/20485?idTenant=7   │
│                                                              │
│  Body: {                                                     │
│    "name": "...",                                           │
│    "listQuestion": [                                        │
│      { "idQuestion": 326941, "weight": 1 },  ← Valid only  │
│      { "idQuestion": 329195, "weight": 1 }   ← Valid only  │
│    ],                                                        │
│    ...                                                       │
│  }                                                           │
└─────────────────────────────────────────────────────────────┘
                          ↓
                    ✅ SUCCESS
```

---

## 🧪 Testing

### **Test Case 1: Fix với import_exam_part_id**

```bash
curl -X POST http://localhost/api/exam_part/fix-invalid-questions \
  -H "Content-Type: application/json" \
  -d '{
    "import_exam_part_id": 123
  }'
```

### **Test Case 2: Check logs**

```bash
tail -f storage/logs/laravel.log | grep "Invalid question found"

# Expected:
# Invalid question found {"ems_question_id":326940,"text":"default","name":"..."}
# Invalid question found {"ems_question_id":329194,"text":"","name":"..."}
```

### **Test Case 3: Verify EMS**

```bash
# Check baikiemtra maxMark đã update
curl https://apiems.hocmai.vn/admin/baikiemtra/20885?idTenant=7 \
  -H "Authorization: Bearer {token}"

# Check test listQuestion
curl https://apiems.hocmai.vn/admin/test/20485?idTenant=7 \
  -H "Authorization: Bearer {token}"
```

---

## 🔍 Logic Chi Tiết

### **1. Invalid Question Detection:**

```php
$text = $dataImport['text'] ?? '';

if (empty($text) || $text === 'default') {
    // ❌ INVALID
    $invalidQuestionIds[] = $emsQuestionId;
} else {
    // ✅ VALID
    $validQuestionIds[] = $emsQuestionId;
}
```

### **2. maxMark Calculation:**

```php
$maxMark = count($validQuestionIds);

// Example:
// Total: 4 questions
// Invalid: 2 questions (326940, 329194)
// Valid: 2 questions (326941, 329195)
// → maxMark = 2
```

### **3. listQuestion Format:**

```php
$listQuestion = [];
foreach ($validQuestionIds as $questionId) {
    $listQuestion[] = [
        'idQuestion' => $questionId,
        'weight' => 1
    ];
}

// Result:
// [
//   { "idQuestion": 326941, "weight": 1 },
//   { "idQuestion": 329195, "weight": 1 }
// ]
```

---

## ⚠️ Important Notes

1. **EMS Credentials:**
   - Sử dụng env variables: `EMS_API_DOMAIN_EMAIL_LOGIN`, `EMS_API_DOMAIN_PASSWORD_LOGIN`
   - Đảm bảo credentials có quyền update baikiemtra và test

2. **Multi-Tenant:**
   - API support multi-tenant
   - Tự động lấy tenant connection
   - `idTenant` lấy từ `data_import._companyShareIdKey`

3. **Logging:**
   - Log invalid questions để review
   - Log EMS API responses
   - Log trong `storage/logs/laravel.log`

4. **Error Handling:**
   - Nếu không có câu hỏi valid → return error
   - Nếu EMS API fail → throw exception
   - Nếu không tìm thấy ImportExamPartEms → 404

---

## 📋 Checklist

- [x] Route created: `POST /api/exam_part/fix-invalid-questions`
- [x] Controller method: `fixInvalidQuestions()`
- [x] Multi-tenant support: ✅
- [x] Logging: ✅
- [x] Error handling: ✅
- [x] Documentation: ✅

---

## 🚀 Usage

```bash
# Call API
curl -X POST http://your-domain/api/exam_part/fix-invalid-questions \
  -H "Content-Type: application/json" \
  -d '{"import_exam_part_id": 123}'

# Check results
# 1. Check response JSON
# 2. Check logs: tail -f storage/logs/laravel.log
# 3. Verify EMS: Check baikiemtra maxMark và test listQuestion
```

---

**API sẵn sàng để test!** 🎉

