# Social Service - Social Relationship Management

> .NET 10 microservice for managing social relationships between users: friendship, following, and blocking.

## Overview

Social Service manages all social relationships between users in the GoodGo Platform:

- **Friendship** - Send/accept/reject friend requests, unfriend
- **Following** - Follow/unfollow users
- **Blocking** - Block/unblock users with optional reason
- **User Profile** - Sync user info from IAM Service

### Architecture & Patterns

| Pattern | Implementation |
|---------|---------------|
| **DDD** | Aggregates, Entities, Value Objects, Domain Events |
| **CQRS** | Commands/Queries separated with MediatR |
| **Clean Architecture** | 3-layer: Domain, Infrastructure, API |
| **EF Core 10** | PostgreSQL with connection resilience |
| **Structured Logging** | Serilog with console and Seq |

## Prerequisites

| Requirement | Version |
|-------------|---------|
| .NET SDK | 10.0.101+ |
| Docker | 24.0+ |
| PostgreSQL | 15+ |

## Quick Start

### Run with Docker

```bash
# Start all services (API + PostgreSQL + Redis)
docker-compose up -d

# View logs
docker-compose logs -f socialservice-api
```

### Run Locally

```bash
# Restore dependencies
dotnet restore

# Build all projects
dotnet build

# Run the API
dotnet run --project src/SocialService.API
```

## Domain Model

### Aggregates

#### 1. Relationship Aggregate
Manages friendship and following relationships between users.

```mermaid
classDiagram
    class Relationship {
        +Guid Id
        +Guid RequesterId
        +Guid AddresseeId
        +RelationshipType Type
        +RelationshipStatus Status
        +DateTime CreatedAt
        +DateTime? UpdatedAt
        +Accept()
        +Reject()
        +Cancel()
        +Remove()
    }
    
    class RelationshipType {
        <<Enumeration>>
        Friendship
        Following
    }
    
    class RelationshipStatus {
        <<Enumeration>>
        Pending
        Accepted
        Rejected
        Cancelled
    }
    
    Relationship --> RelationshipType
    Relationship --> RelationshipStatus
```

**Business Rules:**
- Following is auto-accepted
- Friendship requires confirmation from recipient
- Cannot create relationship with yourself
- Only Pending requests can be Accept/Reject/Cancel
- Only Accepted relationships can be Removed

#### 2. UserBlock Aggregate
Manages user blocking.

| Field | Description |
|-------|-------------|
| `BlockerId` | ID of blocking user |
| `BlockedId` | ID of blocked user |
| `Reason` | Block reason (optional) |
| `CreatedAt` | Block timestamp |

#### 3. UserProfile Aggregate
Caches user info synced from IAM Service.

| Field | Description |
|-------|-------------|
| `UserId` | User ID from IAM |
| `DisplayName` | Display name |
| `AvatarUrl` | Avatar URL |
| `Bio` | User bio |
| `LastSyncedAt` | Last sync time |

## API Endpoints

### Relationships - Friendship

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/v1/relationships/users/{userId}/friends` | Get friend list |
| `POST` | `/api/v1/relationships/friend-requests` | Send friend request |
| `PUT` | `/api/v1/relationships/friend-requests/{id}` | Respond (accept/reject) |
| `GET` | `/api/v1/relationships/users/{id1}/mutual-friends/{id2}` | Get mutual friends |
| `GET` | `/api/v1/relationships/users/{userId}/suggestions` | Friend suggestions |

### Relationships - Following

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/v1/relationships/follow` | Follow user |
| `DELETE` | `/api/v1/relationships/follow` | Unfollow user |

### Block Users

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/v1/blocks` | Block user |
| `DELETE` | `/api/v1/blocks` | Unblock user |
| `GET` | `/api/v1/blocks/users/{userId}` | Get blocked users list |

### Admin Backoffice

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/v1/admin/social/relationships` | Get all relationships (filter, pagination) |
| `GET` | `/api/v1/admin/social/relationships/{id}` | Get relationship details |
| `DELETE` | `/api/v1/admin/social/relationships/{id}` | Admin delete relationship |
| `GET` | `/api/v1/admin/social/blocks` | Get all blocks (pagination) |
| `DELETE` | `/api/v1/admin/social/blocks/{id}` | Admin delete block |
| `GET` | `/api/v1/admin/social/statistics` | Get social statistics |

### Health Endpoints

| Endpoint | Purpose |
|----------|---------|
| `/health` | Full health status |
| `/health/live` | Liveness probe |
| `/health/ready` | Readiness probe |

## Project Structure

```
social-service-net/
├── src/
│   ├── SocialService.API/
│   │   ├── Controllers/
│   │   │   ├── RelationshipsController.cs   # Friends + Following APIs
│   │   │   └── BlocksController.cs          # Block/Unblock APIs
│   │   ├── Application/
│   │   │   ├── Commands/                    # 6 commands
│   │   │   ├── Queries/                     # 4 queries
│   │   │   ├── Behaviors/                   # MediatR pipeline
│   │   │   └── Validations/                 # FluentValidation
│   │   └── Program.cs
│   │
│   ├── SocialService.Domain/
│   │   ├── AggregatesModel/
│   │   │   ├── RelationshipAggregate/       # Relationship, Status, Type
│   │   │   ├── UserBlockAggregate/          # UserBlock
│   │   │   └── UserProfileAggregate/        # UserProfile (IAM sync)
│   │   ├── Events/                          # 7 domain events
│   │   ├── Exceptions/                      # SocialDomainException
│   │   └── SeedWork/                        # Base classes
│   │
│   └── SocialService.Infrastructure/
│       ├── EntityConfigurations/            # EF Core mappings
│       ├── Repositories/                    # 3 repositories
│       ├── Idempotency/                     # Request deduplication
│       └── SocialServiceContext.cs          # DbContext
│
├── tests/
│   ├── SocialService.UnitTests/
│   └── SocialService.FunctionalTests/
│
├── Dockerfile
├── docker-compose.yml
└── docs/
```

## CQRS Pattern

### Commands (Write Operations)

| Command | Description |
|---------|-------------|
| `SendFriendRequestCommand` | Send friend request |
| `RespondToFriendRequestCommand` | Accept/Reject friend request |
| `FollowUserCommand` | Follow user |
| `UnfollowUserCommand` | Unfollow user |
| `BlockUserCommand` | Block user with optional reason |
| `UnblockUserCommand` | Unblock user |

### Queries (Read Operations)

| Query | Description |
|-------|-------------|
| `GetFriendsQuery` | Friend list with pagination |
| `GetMutualFriendsQuery` | Mutual friends between 2 users |
| `GetFriendSuggestionsQuery` | Friend suggestions |
| `GetBlockedUsersQuery` | Blocked users list |

## Domain Events

| Event | Trigger |
|-------|---------|
| `FriendRequestSentDomainEvent` | Friend request sent |
| `FriendshipCreatedDomainEvent` | Friend request accepted |
| `UserFollowedDomainEvent` | User followed |
| `RelationshipStatusChangedDomainEvent` | Status changed |
| `RelationshipRemovedDomainEvent` | Unfriend/unfollow |
| `UserBlockedDomainEvent` | User blocked |
| `UserUnblockedDomainEvent` | User unblocked |

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `ASPNETCORE_ENVIRONMENT` | Environment name | `Development` |
| `DATABASE_URL` | PostgreSQL connection string | - |
| `REDIS_URL` | Redis connection string | - |

### appsettings.json

```json
{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Database=socialservice;Username=postgres;Password=postgres"
  },
  "Serilog": {
    "MinimumLevel": "Information"
  }
}
```

## Testing

```bash
# Run all tests
dotnet test

# Run with coverage
dotnet test /p:CollectCoverage=true

# Run specific test project
dotnet test tests/SocialService.UnitTests
```

## Deployment

### Docker Build

```bash
# Build Docker image
docker build -t socialservice:latest .

# Run container
docker run -p 5000:8080 --env-file .env socialservice:latest
```

## Resources

- [Architecture Documentation](./ARCHITECTURE.md)
- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - Reference architecture
- [DDD with .NET](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/)

## License

Proprietary - GoodGo Platform
