# 🔄 Fluxo de Integração - Guia Detalhado

## Visão Geral do Fluxo

```
ITSM Origem
    │
    ├─(1) Cria Ticket
    │
    └──▶ POST /api/webhooks/events
         {
           "event_type": "ticket.created",
           "source_id": "TICKET-123",
           "data": {
             "title": "Sistema Offline",
             "priority": "high",
             ...
           }
         }

         │
         ├─(2) Valida & Cria Event
         │
         └──▶ RabbitMQ
              (fila: events.received)

              │
              ├─(3) Worker Processa
              │
              ├─▶ Rules Engine
              │   ├─ Avalia condições
              │   ├─ Define roteamento
              │   └─ Aplica SLA
              │
              ├─▶ Transforma Payload
              │   (src: ticket.title → dst: issue_summary)
              │
              └─▶ Chama Integrações
                  ├─ ITSM Parceiro A
                  ├─ ITSM Parceiro B
                  └─ ERP

              │
              ├─(4) Publica Webhooks
              │
              └─▶ Registra Audit
                  └─ Status: processed
                     Duration: 245ms
```

## Passo 1: Recebimento de Evento

### Endpoint
```
POST /api/webhooks/events
Authorization: Bearer <token ou api-key>
Content-Type: application/json
```

### Payload de Entrada
```json
{
  "event_type": "ticket.created",
  "source_system": "itsm-internal",
  "source_id": "TICKET-123",
  "correlation_id": "uuid-optional",
  "data": {
    "title": "Servidor Down",
    "description": "...",
    "priority": "high",
    "category": "infrastructure",
    "assigned_to": "john@company.com"
  }
}
```

### Validações Aplicadas
- ✅ Token válido
- ✅ Schema válido (JSON Schema)
- ✅ Campos obrigatórios presentes
- ✅ Tamanho máximo do payload (10MB)
- ✅ Rate limit não excedido

### Resposta de Sucesso
```json
{
  "status": "accepted",
  "event_id": 1234,
  "correlation_id": "abc-123-def-456",
  "timestamp": "2024-05-27T10:30:00Z"
}
```

HTTP: **202 Accepted**

## Passo 2: Event Processing Pipeline

### A. Event Record Creation
```php
Event::create([
    'event_type' => 'ticket.created',
    'integration_id' => $integration->id,
    'source_system' => 'itsm-internal',
    'source_id' => 'TICKET-123',
    'correlation_id' => $correlationId,
    'payload' => $validatedData,
    'status' => 'received',
]);
```

### B. Event Tracing
```php
$event->recordTrace(
    step: 'received',
    status: 'success',
    metadata: [
        'ip_address' => request()->ip(),
        'user_agent' => request()->userAgent(),
    ]
);
```

### C. Queue Publishing
```php
ProcessEventJob::dispatch($event)
    ->onQueue('default')
    ->delay(0); // immediate
```

## Passo 3: Rules Engine Evaluation

### 3.1 Load Rules
```php
$rules = Rule::where('is_active', true)
    ->where('type', 'routing')
    ->orderBy('priority', 'desc')
    ->get();
```

### 3.2 Evaluate Conditions
```php
$conditions = [
    [
        'field' => 'priority',
        'operator' => 'in',
        'value' => ['high', 'critical']
    ],
    [
        'field' => 'category',
        'operator' => 'equals',
        'value' => 'infrastructure'
    ]
];

if ($rule->evaluateConditions($event->payload)) {
    // Execute actions
}
```

### 3.3 Execute Actions
```php
$actions = [
    [
        'type' => 'route',
        'target' => 'integration_id_5'
    ],
    [
        'type' => 'classify',
        'category' => 'critical'
    ],
    [
        'type' => 'escalate',
        'level' => 2
    ],
    [
        'type' => 'notify',
        'recipients' => ['admin@company.com']
    ]
];
```

### 3.4 Log Execution
```php
RuleExecution::create([
    'rule_id' => $rule->id,
    'event_id' => $event->id,
    'input_data' => $event->payload,
    'output_data' => $result,
    'status' => 'success',
    'execution_time_ms' => $duration,
    'executed_at' => now(),
]);
```

## Passo 4: Payload Transformation

### Mapeamento de Campos
```
Origem (ITSM Internal) │ Transformação │ Destino (Partner A)
─────────────────────────────────────────────────────────
title                  │ direct        │ issue_summary
description            │ trim(255)     │ issue_details
priority               │ map_priority  │ severity
category               │ map_category  │ issue_type
assigned_to            │ email→user_id │ assigned_user_id
created_at             │ direct        │ created_timestamp
```

### Execução
```php
$transformedData = [];

foreach ($mappings as $mapping) {
    $value = data_get($event->payload, $mapping['source_field']);
    
    if ($mapping['transformation']) {
        $value = $this->applyTransformation($value, $mapping['transformation']);
    }
    
    $transformedData[$mapping['target_field']] = $value;
}
```

## Passo 5: Integration Execution

### 5.1 Selecionar Integração
```php
$integration = Integration::find($routingAction['target']);

if (!$integration->isActive()) {
    throw new IntegrationInactiveException();
}
```

### 5.2 Buscar Credenciais
```php
$credential = $integration->getActiveCredential('api_key');
$apiKey = decrypt($credential->encrypted_value);
```

### 5.3 Chamar Endpoint
```php
$response = Http::withHeaders([
    'Authorization' => "Bearer {$apiKey}",
    'Content-Type' => 'application/json',
    'X-Correlation-ID' => $event->correlation_id,
])
->timeout(30)
->post(
    $integration->getEndpoint('create_ticket'),
    $transformedData
);
```

### 5.4 Registrar Resultado
```php
IntegrationLog::create([
    'integration_id' => $integration->id,
    'event_id' => $event->id,
    'endpoint' => $endpoint,
    'method' => 'POST',
    'response_code' => $response->status(),
    'request_body' => $transformedData,
    'response_body' => $response->json(),
    'response_time_ms' => $responseTime,
    'status' => $response->successful() ? 'success' : 'failed',
]);
```

## Passo 6: Webhook Delivery

### 6.1 Buscar Webhooks Interessados
```php
$webhooks = Webhook::where('is_active', true)
    ->get()
    ->filter(fn($w) => $w->matchesEvent($event->event_type));
```

### 6.2 Enviar para Cada Webhook
```php
foreach ($webhooks as $webhook) {
    SendWebhookJob::dispatch($webhook, $event)
        ->onQueue('webhooks');
}
```

### 6.3 Delivery com Retry
```php
try {
    $response = Http::withHeaders($webhook->headers)
        ->timeout(10)
        ->post($webhook->url, [
            'event_type' => $event->event_type,
            'data' => $event->payload,
            'timestamp' => now()->iso8601(),
            'correlation_id' => $event->correlation_id,
        ]);

    WebhookDelivery::create([
        'webhook_id' => $webhook->id,
        'event_id' => $event->id,
        'payload' => $event->payload,
        'status' => 'success',
        'response_code' => $response->status(),
        'delivered_at' => now(),
    ]);
} catch (Exception $e) {
    if ($attempt < $webhook->max_retries) {
        SendWebhookJob::dispatch($webhook, $event)
            ->delay($webhook->retry_delay_seconds)
            ->onQueue('webhooks');
    } else {
        // Send to DLQ
        WebhookDelivery::create([
            'status' => 'failed',
            'error_message' => $e->getMessage(),
        ]);
    }
}
```

## Passo 7: Event Completion

### 7.1 Marcar como Processado
```php
$event->markAsProcessed();

// Atualiza status
$event->update([
    'status' => 'processed',
    'processed_at' => now(),
]);
```

### 7.2 Registrar Métrica
```php
IntegrationMetric::updateOrCreate(
    [
        'integration_id' => $integration->id,
        'metric_date' => now()->date(),
    ],
    [
        'events_processed' => DB::raw('events_processed + 1'),
        'success_rate' => $this->calculateSuccessRate($integration),
    ]
);
```

### 7.3 Audit Log Final
```php
AuditLog::create([
    'action' => 'event_processed',
    'auditable_type' => Event::class,
    'auditable_id' => $event->id,
    'description' => "Event {$event->id} processado com sucesso",
    'metadata' => [
        'duration_ms' => $totalDuration,
        'integrations_called' => $integrationsCount,
        'rules_executed' => $rulesCount,
    ],
    'status' => 'success',
]);
```

## Tratamento de Erros

### Erro 1: Integração Indisponível
```php
catch (IntegrationInactiveException $e) {
    $event->recordTrace(
        'integration_error',
        'failed',
        'Integration is inactive'
    );
    
    // Requeue para retry
    SendWebhookJob::dispatch($webhook, $event)
        ->delay(60)
        ->onQueue('webhooks');
}
```

### Erro 2: Timeout
```php
catch (ConnectException $e) {
    $integration->recordError('Connection timeout');
    // Pula para DLQ após 3 retries
}
```

### Erro 3: Validação Falhou
```php
catch (ValidationException $e) {
    $event->markAsFailed('Payload validation failed');
    $event->recordTrace('validation_error', 'failed', $e->getMessage());
    // Não faz retry automático
}
```

## Exemplo Completo: Ticket de Alta Prioridade

### 1. Entrada
```json
{
  "event_type": "ticket.created",
  "source_system": "itsm-internal",
  "source_id": "TICKET-456",
  "data": {
    "title": "Production Server Critical Alert",
    "priority": "critical",
    "category": "infrastructure",
    "assigned_to": "oncall@company.com"
  }
}
```

### 2. Processamento
- ✅ Evento criado com ID 5678
- ✅ Correlation ID: uuid-abc-123
- ✅ Rule "Critical Infrastructure" matched
- ✅ Payload transformado para Partner A format
- ✅ API chamada para Partner A - Status 200
- ✅ Webhook enviado para "oncall-notifications" - Status 200
- ✅ Métrica atualizada
- ✅ Audit log registrado

### 3. Saída
```json
{
  "status": "processed",
  "correlation_id": "uuid-abc-123",
  "integrations_called": 1,
  "webhooks_triggered": 1,
  "duration_ms": 234,
  "success": true
}
```

## Monitoramento do Fluxo

### Dashboard em Tempo Real
```
Events Recebidos (últimas 24h): 1,245
Events Processados: 1,238
Events Falhados: 7
Taxa de Sucesso: 99.4%

Tempo Médio: 245ms
P95 Latência: 892ms
P99 Latência: 1,523ms

Integrations Ativas: 5
Webhooks Ativos: 12
Rules Ativas: 23
```

### Alertas Automáticos
- Taxa de erro > 5%
- Latência P95 > 10s
- Queue backup > 1000 msgs
- Integração indisponível por >5min
