# Reward Service API 接口文档

## 概述

本文档描述 Reward Service 的 RESTful API 接口。所有接口均需要 JWT 认证（除健康检查外）。

### Base URL

```
http://localhost:3000
```

### 认证方式

所有受保护的端点都需要在请求头中携带 JWT Token：

```
Authorization: Bearer <token>
```

### 通用响应格式

**成功响应**:
```json
{
  "data": { ... },
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "total": 100
  }
}
```

**错误响应**:
```json
{
  "statusCode": 400,
  "message": "错误描述",
  "error": "Bad Request"
}
```

---

## API 端点

### 1. 健康检查

#### GET /health

检查服务健康状态，无需认证。

**请求**:
```http
GET /health HTTP/1.1
Host: localhost:3000
```

**响应** (200 OK):
```json
{
  "status": "ok",
  "service": "reward-service",
  "timestamp": "2024-12-01T00:00:00.000Z"
}
```

---

### 2. 奖励查询

#### GET /rewards/summary

获取当前用户的奖励汇总信息。

**请求**:
```http
GET /rewards/summary HTTP/1.1
Host: localhost:3000
Authorization: Bearer <token>
```

**响应** (200 OK):
```json
{
  "pendingUsdt": 1000,
  "pendingHashpower": 0.5,
  "pendingExpireAt": "2024-12-02T00:00:00.000Z",
  "pendingRemainingTimeMs": 43200000,
  "settleableUsdt": 500,
  "settleableHashpower": 0.2,
  "settledTotalUsdt": 2000,
  "settledTotalHashpower": 1.0,
  "expiredTotalUsdt": 100,
  "expiredTotalHashpower": 0.1
}
```

**响应字段说明**:

| 字段 | 类型 | 描述 |
|------|------|------|
| `pendingUsdt` | number | 待领取 USDT 金额 |
| `pendingHashpower` | number | 待领取算力 |
| `pendingExpireAt` | string \| null | 最近过期时间 (ISO 8601) |
| `pendingRemainingTimeMs` | number | 剩余过期毫秒数 |
| `settleableUsdt` | number | 可结算 USDT 金额 |
| `settleableHashpower` | number | 可结算算力 |
| `settledTotalUsdt` | number | 累计已结算 USDT |
| `settledTotalHashpower` | number | 累计已结算算力 |
| `expiredTotalUsdt` | number | 累计已过期 USDT |
| `expiredTotalHashpower` | number | 累计已过期算力 |

---

#### GET /rewards/details

获取用户奖励明细，支持筛选和分页。

**请求**:
```http
GET /rewards/details?status=PENDING&page=1&pageSize=20 HTTP/1.1
Host: localhost:3000
Authorization: Bearer <token>
```

**查询参数**:

| 参数 | 类型 | 必填 | 描述 |
|------|------|------|------|
| `status` | string | 否 | 奖励状态筛选 |
| `rightType` | string | 否 | 权益类型筛选 |
| `page` | number | 否 | 页码，默认 1 |
| `pageSize` | number | 否 | 每页条数，默认 20 |

**status 枚举值**:
- `PENDING` - 待领取
- `SETTLEABLE` - 可结算
- `SETTLED` - 已结算
- `EXPIRED` - 已过期

**rightType 枚举值**:
- `SHARE_RIGHT` - 分享权益 (500 USDT)
- `PROVINCE_AREA_RIGHT` - 省区域权益 (15 USDT + 1% 算力)
- `PROVINCE_TEAM_RIGHT` - 省团队权益 (20 USDT)
- `CITY_AREA_RIGHT` - 市区域权益 (35 USDT + 2% 算力)
- `CITY_TEAM_RIGHT` - 市团队权益 (40 USDT)
- `COMMUNITY_RIGHT` - 社区权益 (80 USDT)

**响应** (200 OK):
```json
{
  "data": [
    {
      "id": "1",
      "rightType": "SHARE_RIGHT",
      "usdtAmount": 500,
      "hashpowerAmount": 0,
      "rewardStatus": "PENDING",
      "createdAt": "2024-12-01T00:00:00.000Z",
      "expireAt": "2024-12-02T00:00:00.000Z",
      "remainingTimeMs": 86400000,
      "claimedAt": null,
      "settledAt": null,
      "expiredAt": null,
      "memo": "分享权益：来自用户100的认种"
    }
  ],
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "total": 1
  }
}
```

**响应字段说明**:

| 字段 | 类型 | 描述 |
|------|------|------|
| `id` | string | 奖励流水 ID |
| `rightType` | string | 权益类型 |
| `usdtAmount` | number | USDT 金额 |
| `hashpowerAmount` | number | 算力金额 |
| `rewardStatus` | string | 奖励状态 |
| `createdAt` | string | 创建时间 |
| `expireAt` | string \| null | 过期时间 (仅待领取状态) |
| `remainingTimeMs` | number | 剩余过期毫秒数 |
| `claimedAt` | string \| null | 领取时间 |
| `settledAt` | string \| null | 结算时间 |
| `expiredAt` | string \| null | 过期时间 |
| `memo` | string | 备注信息 |

---

#### GET /rewards/pending

获取用户待领取奖励列表，包含倒计时信息。

**请求**:
```http
GET /rewards/pending HTTP/1.1
Host: localhost:3000
Authorization: Bearer <token>
```

**响应** (200 OK):
```json
[
  {
    "id": "1",
    "rightType": "SHARE_RIGHT",
    "usdtAmount": 500,
    "hashpowerAmount": 0,
    "createdAt": "2024-12-01T00:00:00.000Z",
    "expireAt": "2024-12-02T00:00:00.000Z",
    "remainingTimeMs": 43200000,
    "memo": "分享权益：来自用户100的认种（24h内认种可领取）"
  }
]
```

---

### 3. 奖励结算

#### POST /rewards/settle

结算可结算的奖励，支持多种目标币种。

**请求**:
```http
POST /rewards/settle HTTP/1.1
Host: localhost:3000
Authorization: Bearer <token>
Content-Type: application/json

{
  "settleCurrency": "BNB"
}
```

**请求体参数**:

| 参数 | 类型 | 必填 | 描述 |
|------|------|------|------|
| `settleCurrency` | string | 是 | 目标结算币种 |

**支持的结算币种**:
- `BNB` - 币安币
- `OG` - OG Token
- `USDT` - 泰达币
- `DST` - DST Token

**成功响应** (201 Created):
```json
{
  "success": true,
  "settledUsdtAmount": 500,
  "receivedAmount": 0.25,
  "settleCurrency": "BNB",
  "txHash": "0x123abc..."
}
```

**失败响应 - 无可结算奖励** (201 Created):
```json
{
  "success": false,
  "settledUsdtAmount": 0,
  "receivedAmount": 0,
  "settleCurrency": "BNB",
  "error": "没有可结算的收益"
}
```

**失败响应 - 钱包服务错误** (201 Created):
```json
{
  "success": false,
  "settledUsdtAmount": 500,
  "receivedAmount": 0,
  "settleCurrency": "BNB",
  "error": "Insufficient liquidity"
}
```

**验证错误** (400 Bad Request):
```json
{
  "statusCode": 400,
  "message": ["settleCurrency should not be empty"],
  "error": "Bad Request"
}
```

**响应字段说明**:

| 字段 | 类型 | 描述 |
|------|------|------|
| `success` | boolean | 结算是否成功 |
| `settledUsdtAmount` | number | 结算的 USDT 金额 |
| `receivedAmount` | number | 收到的目标币种金额 |
| `settleCurrency` | string | 目标结算币种 |
| `txHash` | string \| undefined | 交易哈希 (成功时返回) |
| `error` | string \| undefined | 错误信息 (失败时返回) |

---

## 错误码

| HTTP Status | 错误码 | 描述 |
|-------------|--------|------|
| 400 | Bad Request | 请求参数验证失败 |
| 401 | Unauthorized | 未认证或 Token 无效 |
| 403 | Forbidden | 无权访问 |
| 404 | Not Found | 资源不存在 |
| 500 | Internal Server Error | 服务器内部错误 |

---

## 数据类型定义

### RewardStatus

```typescript
enum RewardStatus {
  PENDING = 'PENDING',       // 待领取 (24h倒计时)
  SETTLEABLE = 'SETTLEABLE', // 可结算
  SETTLED = 'SETTLED',       // 已结算
  EXPIRED = 'EXPIRED',       // 已过期
}
```

### RightType

```typescript
enum RightType {
  SHARE_RIGHT = 'SHARE_RIGHT',                // 分享权益 500U
  PROVINCE_AREA_RIGHT = 'PROVINCE_AREA_RIGHT',// 省区域权益 15U + 1%算力
  PROVINCE_TEAM_RIGHT = 'PROVINCE_TEAM_RIGHT',// 省团队权益 20U
  CITY_AREA_RIGHT = 'CITY_AREA_RIGHT',        // 市区域权益 35U + 2%算力
  CITY_TEAM_RIGHT = 'CITY_TEAM_RIGHT',        // 市团队权益 40U
  COMMUNITY_RIGHT = 'COMMUNITY_RIGHT',        // 社区权益 80U
}
```

### 权益金额配置

```typescript
const RIGHT_AMOUNTS = {
  SHARE_RIGHT: { usdt: 500, hashpowerPercent: 0 },
  PROVINCE_AREA_RIGHT: { usdt: 15, hashpowerPercent: 1 },
  PROVINCE_TEAM_RIGHT: { usdt: 20, hashpowerPercent: 0 },
  CITY_AREA_RIGHT: { usdt: 35, hashpowerPercent: 2 },
  CITY_TEAM_RIGHT: { usdt: 40, hashpowerPercent: 0 },
  COMMUNITY_RIGHT: { usdt: 80, hashpowerPercent: 0 },
};
```

---

## Swagger 文档

服务启动后，可通过以下地址访问 Swagger UI：

```
http://localhost:3000/api
```

---

## 使用示例

### cURL 示例

```bash
# 健康检查
curl http://localhost:3000/health

# 获取奖励汇总
curl -H "Authorization: Bearer <token>" \
  http://localhost:3000/rewards/summary

# 获取奖励明细 (筛选待领取)
curl -H "Authorization: Bearer <token>" \
  "http://localhost:3000/rewards/details?status=PENDING&page=1&pageSize=10"

# 结算奖励
curl -X POST \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"settleCurrency": "BNB"}' \
  http://localhost:3000/rewards/settle
```

### JavaScript 示例

```javascript
const BASE_URL = 'http://localhost:3000';
const TOKEN = 'your-jwt-token';

// 获取奖励汇总
async function getRewardSummary() {
  const response = await fetch(`${BASE_URL}/rewards/summary`, {
    headers: {
      'Authorization': `Bearer ${TOKEN}`,
    },
  });
  return response.json();
}

// 结算奖励
async function settleRewards(currency) {
  const response = await fetch(`${BASE_URL}/rewards/settle`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${TOKEN}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ settleCurrency: currency }),
  });
  return response.json();
}
```
