# EMS Import - Error Handling Guide

## 🎯 **XỬ LÝ CÁC LOẠI RESPONSE**

### **1. Question Not Found (404)**

**Response từ EMS:**
```json
{
    "status": false,
    "message": "Không tìm thấy"
}
```

**Xử lý:**
- ✅ **KHÔNG phải lỗi**
- ✅ Skip question này
- ✅ Count vào `not_found`
- ✅ Log: "Question not found in EMS"

**Lý do:**
- Có thể question đã bị xóa trong EMS
- Hoặc ID không tồn tại
- Không cần retry

---

### **2. Question Already Exists (409)**

**Response từ LMS:**
```json
{
    "status": false,
    "message": "Question already exists in database",
    "data": {
        "id": 123,
        "ems_question_id": 246415,
        "status": 0
    }
}
```

**Xử lý:**
- ✅ Skip question này
- ✅ Count vào `skipped`
- ✅ Không import lại

---

### **3. Real Errors**

**Network Error:**
```json
{
    "status": false,
    "message": "Could not connect to EMS: Connection timeout"
}
```

**Server Error (500):**
```json
{
    "status": false,
    "message": "API returned error code: 500",
    "response": {...}
}
```

**Xử lý:**
- ❌ Đây là lỗi thật sự
- ❌ Count vào `errors`
- ✅ Nên retry sau

---

## 📊 **PHÂN LOẠI TRONG BATCH IMPORT**

### **Response Structure:**

```json
{
    "status": true,
    "message": "Batch import completed",
    "data": {
        "total_processed": 100,
        "imported": 85,           // ✅ Thành công
        "skipped": 10,            // ℹ️ Đã tồn tại trong DB
        "not_found": 3,           // ℹ️ Không tìm thấy trong EMS
        "errors": 2,              // ❌ Lỗi thật sự
        "start_id": 1,
        "end_id": 100
    },
    "summary": {
        "success_rate": "85%",
        "details": "Imported: 85, Already exists: 10, Not found in EMS: 3, Errors: 2"
    }
}
```

---

## 🔍 **PHÂN TÍCH TỪNG LOẠI**

### **1. Imported (85/100)** ✅

```
Question IDs: 1-85
- Lấy thông tin từ EMS thành công
- Lưu vào database thành công
- Status = 0 (NEW)
- Ready để process tiếp
```

**Action:** ✅ Good! Tiếp tục process

---

### **2. Skipped (10/100)** ℹ️

```
Question IDs: 86-95
- Đã tồn tại trong database
- Có thể đã import trước đó
- Không import lại (tránh duplicate)
```

**Action:** 
- ℹ️ Bình thường
- Có thể bỏ qua
- Hoặc update data nếu cần:

```php
$existing = EmsQuestion::where('ems_question_id', 86)->first();
$existing->update([
    'question_data' => $newData, // Update với data mới
]);
```

---

### **3. Not Found (3/100)** ℹ️

```
Question IDs: 96-98
- Không tồn tại trong EMS
- Có thể đã bị xóa
- Hoặc ID gap (không liên tục)
```

**Ví dụ:**
```
Total questions: 380,246
Last ID: 381,857

Gap: 381,857 - 380,246 = 1,611 questions
→ Có 1,611 IDs không tồn tại (đã xóa hoặc skip)
```

**Action:**
- ℹ️ Bình thường
- Bỏ qua, không cần xử lý
- Log để tham khảo

---

### **4. Errors (2/100)** ❌

```
Question IDs: 99-100
- Lỗi network (timeout, connection refused)
- Lỗi server EMS (500, 503)
- Lỗi database local (constraint, disk full)
```

**Action:**
- ❌ Cần xử lý
- ✅ Retry sau
- ✅ Check logs để debug

---

## 🔄 **RETRY STRATEGY**

### **Auto Retry cho Errors:**

```bash
# Bước 1: Import batch đầu tiên
curl -X POST '/api/speakup/import-questions-batch' \
  -d '{"start_id": 1, "end_id": 1000}'

# Response: errors = 20

# Bước 2: Lấy danh sách errors từ logs
# (Hoặc tạo API để list errors)

# Bước 3: Retry từng question có error
for id in 45 67 89 ...; do
    curl -X POST "/api/speakup/import-question?idQuestion=$id"
    sleep 1
done
```

---

### **Hoặc tạo API Retry:**

```php
// Trong Controller
public function retryErrors(Request $request)
{
    // Get list of error IDs from logs or tracking table
    $errorIds = [45, 67, 89, ...];
    
    $retried = 0;
    $success = 0;
    $stillError = 0;
    
    foreach ($errorIds as $id) {
        try {
            // Retry import
            $result = $this->importQuestion(
                new Request(['idQuestion' => $id])
            );
            
            $data = json_decode($result->getContent(), true);
            
            if ($data['status']) {
                $success++;
            } else {
                $stillError++;
            }
            
            $retried++;
            sleep(1);
            
        } catch (\Exception $e) {
            $stillError++;
        }
    }
    
    return response()->json([
        'retried' => $retried,
        'success' => $success,
        'still_error' => $stillError,
    ]);
}
```

---

## 📊 **EXPECTED RESULTS**

### **Khi import 380K questions:**

```
Ví dụ phân bố (ước tính):

Total processed: 381,857 IDs
├─ Imported:      370,000 (96.9%)  ✅
├─ Not found:       1,611 (0.4%)   ℹ️ (Gap IDs)
├─ Skipped:             0 (0%)     ℹ️ (Lần đầu import)
└─ Errors:            246 (0.06%)  ❌ (Network issues)

Success rate: 96.9%
```

**Lý do có not_found:**
- Total questions: 380,246
- Last ID: 381,857
- Gap: 1,611 IDs không tồn tại

**Lý do có errors:**
- Network timeout (EMS quá tải)
- Rate limiting
- Temporary server issues

---

## ✅ **BEST PRACTICES**

### **1. Import từng đợt nhỏ:**

```bash
# KHÔNG làm thế này (quá lớn):
start_id=1, end_id=381857  # ❌ 381K questions 1 lúc!

# Làm thế này (từng batch):
start_id=1,     end_id=1000    # ✅ 1K questions
start_id=1001,  end_id=2000    # ✅ 1K questions
...
```

**Lý do:**
- Dễ track progress
- Dễ retry nếu lỗi
- Không timeout
- Không overload server

---

### **2. Monitor progress:**

```bash
# Mỗi 10 batches, check stats
curl '/api/speakup/import-stats'
```

---

### **3. Handle errors:**

```bash
# Sau khi import xong, retry errors
# (Tạo script riêng để retry)
```

---

### **4. Logging:**

```bash
# Monitor logs realtime
tail -f storage/logs/laravel.log | grep "Batch import"

# Count imported
grep "Question imported successfully" storage/logs/laravel.log | wc -l

# Count errors
grep "Get question info failed" storage/logs/laravel.log | wc -l
```

---

## 🎯 **EXAMPLE RESPONSES**

### **Batch Import - Mixed Results:**

```json
{
    "status": true,
    "message": "Batch import completed",
    "data": {
        "total_processed": 100,
        "imported": 85,
        "skipped": 10,
        "not_found": 3,
        "errors": 2,
        "start_id": 1,
        "end_id": 100
    },
    "summary": {
        "success_rate": "85%",
        "details": "Imported: 85, Already exists: 10, Not found in EMS: 3, Errors: 2"
    }
}
```

**Giải thích:**
- 85 questions: ✅ Import thành công
- 10 questions: ℹ️ Đã có trong DB (import lần 2)
- 3 questions: ℹ️ Không tồn tại trong EMS (ID gap)
- 2 questions: ❌ Lỗi thật sự (cần retry)

---

### **Single Import - Not Found:**

```json
{
    "status": false,
    "message": "Question not found in EMS",
    "ems_question_id": 246415
}
```

**Action:** Bỏ qua, question này không tồn tại.

---

### **Single Import - Success:**

```json
{
    "status": true,
    "message": "Question imported successfully",
    "data": {
        "id": 1,
        "ems_question_id": 246415,
        "name": "Question name...",
        "status": 0,
        "status_name": "Mới tạo"
    }
}
```

**Action:** ✅ Thành công! Tiếp tục xử lý.

---

## 🔧 **TROUBLESHOOTING**

### **Nếu có nhiều errors (> 5%):**

**Nguyên nhân:**
- EMS server quá tải
- Network không ổn định
- Rate limiting

**Giải pháp:**
1. Giảm batch size: 1000 → 100
2. Tăng sleep time: 1s → 5s
3. Retry sau vài phút
4. Check EMS server status

---

### **Nếu có nhiều not_found (> 2%):**

**Nguyên nhân:**
- ID range không đúng
- Questions đã bị xóa hàng loạt

**Giải pháp:**
1. Check API `/question-total` để biết ID range chính xác
2. Bỏ qua not_found, chỉ import questions tồn tại

---

## 📝 **SUMMARY**

**Phân loại kết quả:**

| Type | Meaning | Count in | Action |
|------|---------|----------|--------|
| **Imported** | Import thành công | `imported` | ✅ Process tiếp |
| **Skipped** | Đã tồn tại trong DB | `skipped` | ℹ️ Bỏ qua |
| **Not Found** | Không có trong EMS | `not_found` | ℹ️ Bỏ qua |
| **Errors** | Lỗi thật sự | `errors` | ❌ Retry |

**Success Rate:**
```
Success = Imported / Total Processed
Ví dụ: 85 / 100 = 85%
```

**Acceptable Rates:**
- Imported: 95%+  ✅ Excellent
- Not found: 1-2% ✅ Normal (ID gaps)
- Errors: < 1%   ✅ Acceptable
- Errors: > 5%   ⚠️ Need investigation

