# API .NET + Next.js Example

Exemplo de arquitetura full-stack com .NET API backend e Next.js frontend.

## Stack

| Camada | Tecnologia |
|--------|------------|
| **Frontend** | Next.js 14 (App Router) |
| **Backend** | .NET 8 Minimal APIs |
| **Database** | SQL Server / PostgreSQL |
| **Auth** | Clerk (SSO) |
| **API Communication** | REST + React Query |
| **Infra** | Azure Container Apps |

## Arquitetura

```
┌─────────────────────────────────────────────────────────────┐
│                    Next.js Frontend                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │   Pages     │  │ Components  │  │    Hooks            │  │
│  │  /dashboard │  │ DataTable   │  │ useProducts()       │  │
│  │  /products  │  │ Forms       │  │ useOrders()         │  │
│  │  /orders    │  │ Charts      │  │ useAuth()           │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                              │
                              │ REST API
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      .NET API                                │
│  ┌─────────────────────────────────────────────────────┐    │
│  │  Endpoints: /api/products, /api/orders, /api/users  │    │
│  └─────────────────────────────────────────────────────┘    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────┐  │
│  │  Services    │  │  Validators  │  │  Middlewares     │  │
│  └──────────────┘  └──────────────┘  └──────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                     Infrastructure                           │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────┐  │
│  │  EF Core     │  │  Redis       │  │  Blob Storage    │  │
│  │  Repository  │  │  Cache       │  │  (files)         │  │
│  └──────────────┘  └──────────────┘  └──────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

## Estrutura de Pastas

```
project/
├── src/
│   ├── api/                          # .NET Backend
│   │   ├── Api/
│   │   │   ├── Endpoints/
│   │   │   │   ├── ProductEndpoints.cs
│   │   │   │   ├── OrderEndpoints.cs
│   │   │   │   └── UserEndpoints.cs
│   │   │   ├── Middleware/
│   │   │   └── Program.cs
│   │   ├── Application/
│   │   │   ├── Services/
│   │   │   └── Validators/
│   │   ├── Domain/
│   │   │   ├── Entities/
│   │   │   └── Interfaces/
│   │   └── Infrastructure/
│   │       ├── Data/
│   │       └── Repositories/
│   │
│   └── web/                          # Next.js Frontend
│       ├── app/
│       │   ├── (auth)/
│       │   │   ├── sign-in/
│       │   │   └── sign-up/
│       │   ├── (dashboard)/
│       │   │   ├── dashboard/
│       │   │   ├── products/
│       │   │   └── orders/
│       │   ├── layout.tsx
│       │   └── page.tsx
│       ├── components/
│       │   ├── ui/
│       │   └── shared/
│       ├── hooks/
│       │   ├── use-products.ts
│       │   └── use-orders.ts
│       ├── lib/
│       │   ├── api-client.ts
│       │   └── utils.ts
│       └── types/
│
├── infra/                            # Infrastructure as Code
│   ├── main.bicep
│   └── modules/
│
└── docker-compose.yml
```

## Quick Start

### Backend (.NET)

```bash
cd src/api
dotnet restore
dotnet ef database update
dotnet run
```

### Frontend (Next.js)

```bash
cd src/web
npm install
npm run dev
```

### Docker Compose

```bash
docker-compose up -d
```

## Features

### Backend
- Minimal APIs com OpenAPI
- FluentValidation para validação
- EF Core com Repository Pattern
- JWT Bearer Authentication
- Health Checks
- Structured Logging

### Frontend
- App Router (Next.js 14)
- Server Components + Client Components
- React Query para data fetching
- Tailwind CSS + shadcn/ui
- Form handling com React Hook Form
- TypeScript estrito

## Autenticação

### Fluxo

```mermaid
sequenceDiagram
    participant User
    participant NextJS
    participant Clerk
    participant API

    User->>NextJS: Acessa /sign-in
    NextJS->>Clerk: Redirect para Clerk
    User->>Clerk: Login
    Clerk-->>NextJS: JWT Token
    NextJS->>API: Request com Bearer Token
    API->>Clerk: Valida token (JWKS)
    API-->>NextJS: Response
    NextJS-->>User: Renderiza página
```

### Configuração Clerk (Next.js)

```typescript
// middleware.ts
import { clerkMiddleware } from "@clerk/nextjs/server";

export default clerkMiddleware();

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
```

### Configuração JWT (API)

```csharp
// Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Clerk:Authority"];
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = false,
            NameClaimType = "sub"
        };
    });
```

## API Client (Frontend)

```typescript
// lib/api-client.ts
import { auth } from "@clerk/nextjs/server";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL;

export async function apiClient<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const { getToken } = auth();
  const token = await getToken();

  const response = await fetch(`${API_BASE_URL}${endpoint}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
      ...options.headers,
    },
  });

  if (!response.ok) {
    throw new Error(`API Error: ${response.statusText}`);
  }

  return response.json();
}
```

## Custos Estimados

| Recurso | Tier | Custo/mês |
|---------|------|-----------|
| Container App (API) | Consumption | ~$0-5 |
| Container App (Web) | Consumption | ~$0-5 |
| SQL Database | Free 32GB | $0 |
| Clerk | Free 10k MAU | $0 |

**Total**: < $10/mês para MVPs

---

*MORPH-SPEC by Polymorphism Tech*
