# Notification API Documentation

## Tổng quan các thay đổi

### 1. Hàm `markAsRead` đã được cập nhật
- Sau khi đánh dấu notification là đã đọc, hệ thống sẽ tự động gọi API của bên thứ 3 để thông báo
- Gửi thông tin về message_id, user_id, tổng số notification của user (distinct count theo id), time_read, phone, email

### 2. Hàm `getUnreadCount` đã được cập nhật
- Trả về số lượng notification chưa đọc
- Trả về 5 notification chưa đọc mới nhất

### 3. API mới `receiveReadCallback`
- Endpoint để nhận callback từ bên thứ 3 (nếu họ muốn gửi xác nhận ngược lại)
- Ghi log tất cả các request từ bên thứ 3

## Cấu hình

### Environment Variables

Thêm vào file `.env`:

```bash
# URL của API bên thứ 3 để gửi thông báo khi user đọc notification
NOTIFICATION_CALLBACK_URL=https://lmstest.hocmai.net/api/notification/receive
```

## API Endpoints

### 1. Mark Notification as Read
**POST** `/api/notification/mark-as-read/{id}`

**Response:**
```json
{
  "status": "ok",
  "message": "Notification marked as read"
}
```

**Side Effect:**
- Sau khi đánh dấu đã đọc, hệ thống sẽ gọi API của bên thứ 3 với payload:

```json
{
  "message_id": "1",
  "data": {
    "user_id": 1234,
    "total": 15
  },
  "time_read": "2025-10-10 18:00:00",
  "phone": "0123456789",
  "email": "user@example.com"
}
```

**Lưu ý:** `total` là tổng số lượng bản ghi notification của user trong bảng `notification_receive_users` (distinct by id), KHÔNG phải chỉ số notification chưa đọc.

### 2. Get Unread Count và Latest Notifications
**POST** `/api/notification/get-unread-count`

**Request Body:**
```json
{
  "user_id": 1234
}
```

**Response:**
```json
{
  "status": "ok",
  "unread_count": 10,
  "latest_notifications": [
    {
      "id": 1,
      "title": "Thông báo mới",
      "body": "Nội dung thông báo",
      "data": {...},
      "read_at": null,
      "created_at": "2025-10-11 10:00:00"
    },
    ...
  ]
}
```

### 3. Receive Callback từ Bên Thứ 3 (NEW)
**POST** `/api/notification/receive-callback`

**Request Body:**
```json
{
  "message_id": "1",
  "data": {
    "user_id": 1234,
    "total": 1000
  },
  "time_read": "2025-10-10 18:00:00",
  "phone": "1234",
  "email": "email@gmail.com"
}
```

**Response:**
```json
{
  "status": "ok",
  "message": "Callback received successfully"
}
```

**Ví dụ cURL:**
```bash
curl --location 'https://lmstest.hocmai.net/api/notification/receive-callback' \
--header 'Content-Type: application/json' \
--data-raw '{
    "message_id": "1",
    "data": {
        "user_id": 1234,
        "total": 1000
    },
    "time_read": "2025-10-10 18:00:00",
    "phone": "1234",
    "email": "email@gmail.com"
}'
```

## Flow Diagram

```
User đánh dấu đã đọc
    ↓
markAsRead() được gọi
    ↓
Cập nhật read_at trong database
    ↓
Đếm tổng số notification của user (distinct by id)
    ↓
Gọi notifyThirdParty()
    ↓
Gửi HTTP POST request đến NOTIFICATION_CALLBACK_URL
    ↓
Log kết quả (thành công hoặc lỗi)
    ↓
Trả về response cho client
```

## Logging

Tất cả các hoạt động được ghi log vào:
- `/storage/logs/notification/YYYY-MM-DD.log`

Log bao gồm:
- Request gửi đến bên thứ 3
- Response từ bên thứ 3
- Callback nhận được từ bên thứ 3
- Các lỗi xảy ra

## Lưu ý

1. **Timeout**: Request gửi đến bên thứ 3 có timeout là 10 giây
2. **Error Handling**: Nếu gọi API bên thứ 3 thất bại, hệ thống sẽ log lỗi nhưng KHÔNG làm fail request chính của user
3. **Async Processing**: Nếu muốn tăng performance, có thể đưa việc gọi API bên thứ 3 vào Job Queue
4. **Security**: Nên thêm authentication/authorization cho endpoint `/api/notification/receive-callback` để tránh spam

## Testing

### Test markAsRead với callback
```bash
# 1. Mark notification as read
curl -X POST http://localhost/api/notification/mark-as-read/1 \
  -H "Content-Type: application/json"

# 2. Check log file
tail -f storage/logs/notification/$(date +%Y-%m-%d).log
```

### Test receive callback
```bash
curl -X POST http://localhost/api/notification/receive-callback \
  -H "Content-Type: application/json" \
  -d '{
    "message_id": "1",
    "data": {
      "user_id": 1234,
      "total": 10
    },
    "time_read": "2025-10-11 12:00:00",
    "phone": "0123456789",
    "email": "test@example.com"
  }'
```

## Giải thích Payload gửi đến bên thứ 3

```json
{
  "message_id": "1",
  "data": {
    "user_id": 1234,
    "total": 15
  },
  "time_read": "2025-10-10 18:00:00",
  "phone": "0123456789",
  "email": "user@example.com"
}
```

**Ý nghĩa các field:**
- `message_id`: ID của message gốc từ hệ thống gửi notification
- `user_id`: ID của user đã đọc notification  
- `total`: Tổng số lượng notification của user này (count distinct id từ bảng `notification_receive_users`)
- `time_read`: Thời gian user đánh dấu notification là đã đọc (format: Y-m-d H:i:s)
- `phone`: Số điện thoại của user
- `email`: Email của user

**Lưu ý quan trọng:** `total` là tổng số tất cả các notification (cả đã đọc và chưa đọc) của user, KHÔNG phải chỉ số notification chưa đọc.

## Future Improvements

1. **Queue Integration**: Đưa việc gọi API bên thứ 3 vào Queue để không block request chính
2. **Retry Mechanism**: Thêm retry logic nếu API bên thứ 3 timeout hoặc lỗi
3. **Authentication**: Thêm API key hoặc JWT cho endpoint callback
4. **Webhooks Management**: Tạo UI để quản lý các webhook URL
5. **Rate Limiting**: Thêm rate limiting cho callback endpoint

