# Mission Service .NET

> Mission & Task gamification service for GoodGo Platform.

📖 **See also:** [Detailed Architecture Documentation](./ARCHITECTURE.md)

## Overview

The **Mission Service** manages gamification missions and tasks, enabling users to earn rewards through various activities on the GoodGo platform.

### Key Features

| Feature | Description |
|---------|-------------|
| 🎬 **Watch Video** | Earn rewards by watching videos - Pay per view |
| 💰 **Pay Per Click** | Earn points by clicking ads/links |
| 📤 **Pay Per Upload** | Get rewarded for uploading UGC content |
| 👥 **Invite Friends** | Earn bonus when friends complete missions |
| 📅 **Daily Check-in** | Daily check-in with streak bonuses |
| ❤️ **Social Actions** | Like, Share, Subscribe to social channels |

---

## Architecture Design

### System Architecture

```mermaid
%%{init: {'theme':'dark'}}%%
graph TD
    subgraph Gateway["🌐 API Gateway"]
        Traefik[Traefik]
    end
    
    subgraph Mission["📋 Mission Service"]
        API[API Layer]
        Domain[Domain Layer]
        Infra[Infrastructure]
    end
    
    subgraph External["🔗 External Services"]
        IAM[IAM Service]
        Wallet[Wallet Service]
        Mining[Mining Service]
        Social[Social Service]
        Storage[Storage Service]
    end
    
    subgraph Data["💾 Data Layer"]
        DB[(PostgreSQL)]
        Redis[(Redis)]
        RabbitMQ[RabbitMQ]
    end
    
    Traefik --> API
    API --> Domain
    Domain --> Infra
    Infra --> DB
    Infra --> Redis
    Infra --> RabbitMQ
    
    Mission <--> IAM
    Mission --> Wallet
    Mission <--> Mining
    Mission <--> Social
    Mission <--> Storage
    
    style Gateway fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
    style Mission fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:3px
    style External fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
    style Data fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
```

### Clean Architecture Structure

```
mission-service-net/
├── src/
│   ├── MissionService.API/               # API Layer
│   │   ├── Controllers/
│   │   │   ├── MissionsController.cs     # Mission management
│   │   │   ├── TasksController.cs        # Task execution
│   │   │   ├── CheckInController.cs      # Daily check-in
│   │   │   └── RewardsController.cs      # Reward claims
│   │   └── Application/
│   │       ├── Commands/                 # Write operations
│   │       ├── Queries/                  # Read operations
│   │       └── IntegrationEvents/        # External events
│   │
│   ├── MissionService.Domain/            # Domain Layer
│   │   ├── AggregatesModel/
│   │   │   ├── MissionAggregate/         # Mission definitions
│   │   │   ├── TaskAggregate/            # Task executions
│   │   │   ├── CheckInAggregate/         # Daily check-in
│   │   │   └── RewardAggregate/          # Reward tracking
│   │   ├── Events/                       # Domain events
│   │   └── Services/                     # Domain services
│   │
│   └── MissionService.Infrastructure/    # Infrastructure
│       ├── EntityConfigurations/         # EF Core mappings
│       ├── Repositories/                 # Data access
│       └── ExternalServices/             # API clients
│
├── tests/
├── docs/
└── Dockerfile
```

---

## Domain Model

### Core Aggregates

```mermaid
%%{init: {'theme':'dark'}}%%
classDiagram
    class Mission {
        +Guid Id
        +string Code
        +LocalizedString Title
        +MissionType Type
        +MissionReward Reward
        +FrequencyType Frequency
        +MissionStatus Status
        +Activate()
        +Pause()
        +ValidateCompletion()
    }
    
    class UserTask {
        +Guid Id
        +Guid UserId
        +Guid MissionId
        +TaskStatus Status
        +TaskProgress Progress
        +TaskEvidence Evidence
        +Start()
        +UpdateProgress()
        +Complete()
        +ClaimReward()
    }
    
    class UserCheckIn {
        +Guid Id
        +Guid UserId
        +int CurrentStreak
        +int LongestStreak
        +DateOnly LastCheckInDate
        +CheckIn()
        +GetStreakBonus()
    }
    
    Mission "1" --> "*" UserTask : generates
    UserTask --> UserCheckIn : may trigger
```

### Mission Types

```mermaid
%%{init: {'theme':'dark'}}%%
flowchart LR
    subgraph Types["📋 Mission Types"]
        Video["🎬 Watch Video"]
        Click["💰 Pay Per Click"]
        Upload["📤 Pay Per Upload"]
        Invite["👥 Invite Friends"]
        CheckIn["📅 Daily Check-in"]
        Social["❤️ Social Actions"]
    end
    
    style Video fill:#E74C3C,color:#ECF0F1,stroke:#C0392B,stroke-width:2px
    style Click fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
    style Upload fill:#9B59B6,color:#ECF0F1,stroke:#8E44AD,stroke-width:2px
    style Invite fill:#2ECC71,color:#ECF0F1,stroke:#27AE60,stroke-width:2px
    style CheckIn fill:#F39C12,color:#ECF0F1,stroke:#E67E22,stroke-width:2px
    style Social fill:#E91E63,color:#ECF0F1,stroke:#C2185B,stroke-width:2px
```

---

## Daily Check-in System

### 🔥 Streak Bonus

```mermaid
%%{init: {'theme':'dark'}}%%
flowchart LR
    subgraph Streak["📅 Streak Tiers"]
        D1["Day 1-6<br/>2 MP"] --> D7["Day 7<br/>🎁 +20 MP"]
        D7 --> D14["Day 14<br/>🎁 +35 MP"]
        D14 --> D21["Day 21<br/>🎁 +50 MP"]
        D21 --> D30["Day 30<br/>👑 +100 MP"]
    end
    
    style D1 fill:#7F8C8D,color:#ECF0F1,stroke:#5D6D7E,stroke-width:2px
    style D7 fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
    style D14 fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
    style D21 fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
    style D30 fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:3px
```

| Streak | Daily Points | Milestone Bonus |
|--------|--------------|-----------------|
| Day 1-6 | 2 MP | - |
| Day 7 | 3 MP | 🎁 20 MP bonus |
| Day 8-13 | 3 MP | - |
| Day 14 | 4 MP | 🎁 35 MP bonus |
| Day 15-20 | 4 MP | - |
| Day 21 | 5 MP | 🎁 50 MP bonus |
| Day 22-29 | 5 MP | - |
| Day 30 | 10 MP | 👑 100 MP + Badge |

---

## API Endpoints

### Mission APIs

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/v1/missions` | List available missions |
| `GET` | `/api/v1/missions/{id}` | Get mission details |
| `GET` | `/api/v1/missions/category/{category}` | Get missions by category |
| `POST` | `/api/v1/missions/{id}/start` | Start a mission task |
| `PUT` | `/api/v1/missions/tasks/{taskId}/progress` | Update task progress |
| `POST` | `/api/v1/missions/tasks/{taskId}/claim` | Claim task reward |

### Check-in APIs

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/v1/checkins` | Daily check-in |
| `GET` | `/api/v1/checkins/status` | Check-in status |
| `GET` | `/api/v1/checkins/history` | Check-in history (monthly) |
| `GET` | `/api/v1/checkins/leaderboard` | Streak leaderboard |
| `GET` | `/api/v1/checkins/config` | Streak bonus configuration |

### Admin Backoffice APIs

#### 📋 Mission Management

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/v1/admin/missions` | List all missions |
| `POST` | `/api/v1/admin/missions` | Create new mission |
| `GET` | `/api/v1/admin/missions/{id}` | Get mission details |
| `POST` | `/api/v1/admin/missions/{id}/activate` | Activate mission |
| `POST` | `/api/v1/admin/missions/{id}/pause` | Pause mission |
| `POST` | `/api/v1/admin/missions/{id}/archive` | Archive mission |

#### 👥 Check-in Management

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/v1/admin/checkins/users/{userId}` | Get user check-in details |
| `POST` | `/api/v1/admin/checkins/users/{userId}/reset-streak` | Reset user streak |
| `GET` | `/api/v1/admin/checkins/top-streaks` | Get top streak leaderboard |

#### ✅ Task Management

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/v1/admin/tasks/pending-verification` | Get pending verification tasks |
| `GET` | `/api/v1/admin/tasks/users/{userId}` | Get user's tasks |
| `POST` | `/api/v1/admin/tasks/{taskId}/approve` | Approve task |
| `POST` | `/api/v1/admin/tasks/{taskId}/reject` | Reject task |

---

## Integration Points

### Service Dependencies

```mermaid
%%{init: {'theme':'dark'}}%%
flowchart LR
    subgraph Mission["📋 Mission Service"]
        M[Mission Service]
    end
    
    subgraph Auth["🔐 Auth"]
        IAM[IAM Service]
    end
    
    subgraph Rewards["💰 Rewards"]
        Wallet[Wallet Service]
        Mining[Mining Service]
    end
    
    subgraph Social["👥 Social"]
        SocialSvc[Social Service]
        Storage[Storage Service]
    end
    
    IAM -->|JWT Auth| M
    M -->|Grant Points| Wallet
    M <-->|Referral Sync| Mining
    M <-->|Friend Check| SocialSvc
    M <-->|Media| Storage
    
    style Mission fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:3px
    style Auth fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
    style Rewards fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
    style Social fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
```

### Integration Events

| Event | Publisher | Consumer | Description |
|-------|-----------|----------|-------------|
| `MissionCompletedEvent` | Mission | Wallet | User completed mission |
| `CheckInCompletedEvent` | Mission | Wallet | Daily check-in done |
| `UserRegisteredEvent` | IAM | Mission | Create user profile |
| `ReferralActivatedEvent` | Mining | Mission | Sync invite status |

---

## Tech Stack

| Component | Technology | Purpose |
|-----------|------------|---------|
| **Framework** | .NET 10 | Latest LTS framework |
| **API Layer** | Controllers + MediatR | CQRS pattern |
| **Database** | PostgreSQL + EF Core 10 | Persistent storage |
| **Caching** | Redis + HybridCache | L1+L2 caching |
| **Message Queue** | RabbitMQ (MassTransit) | Integration events |
| **Scheduler** | Hangfire | Background jobs |
| **Validation** | FluentValidation | Request validation |
| **API Docs** | Swagger/OpenAPI | Documentation |

---

## Configuration

### Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `DATABASE_URL` | PostgreSQL connection | Yes |
| `REDIS_URL` | Redis connection | Yes |
| `RABBITMQ_URL` | RabbitMQ connection | Yes |
| `JWT_AUTHORITY` | JWT issuer URL | Yes |
| `MAX_DAILY_TASKS` | Max tasks per day | No |

---

## Security & Anti-Fraud

### Fraud Prevention

```mermaid
%%{init: {'theme':'dark'}}%%
flowchart TD
    Request([🚀 Request]) --> Rate{⏱️ Rate Limit}
    Rate -->|Exceeded| Block[❌ Block]
    Rate -->|OK| Device{🔍 Device Check}
    Device -->|Suspicious| Flag[⚠️ Flag]
    Device -->|OK| Verify{✅ Verify Evidence}
    Verify -->|Invalid| Reject[❌ Reject]
    Verify -->|Valid| Reward[🎁 Grant Reward]
    
    style Block fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
    style Reject fill:#E74C3C,color:#ECF0F1,stroke:#C0392B,stroke-width:2px
    style Reward fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
```

| Measure | Description |
|---------|-------------|
| **Rate Limiting** | Max tasks per user per day |
| **Cooldown** | Min time between completions |
| **Device Fingerprint** | Track multi-account |
| **Evidence Validation** | AI + Manual review for UGC |

---

## Roadmap

### Phase 1: Core (Week 1-2)
- [ ] Project setup
- [ ] Domain model
- [ ] Database schema

### Phase 2: Daily Check-in (Week 3)
- [ ] Check-in aggregate
- [ ] Streak calculation
- [ ] Milestone rewards

### Phase 3: Watch Video (Week 4-5)
- [ ] Video mission type
- [ ] Progress tracking
- [ ] Duration verification

### Phase 4: Social Actions (Week 6-7)
- [ ] Social platform configs
- [ ] Verification methods
- [ ] OAuth integration

### Phase 5: Advanced (Week 8+)
- [ ] Pay per click/upload
- [ ] Invite friends
- [ ] Admin analytics
