# Deployment no Azure (AKS)

Guia para deploy do Monetarie PIX no Microsoft Azure usando AKS (Azure Kubernetes Service), Azure Database for PostgreSQL, Azure Cache for Redis e NATS em Azure VMs.

## Pre-requisitos

- Conta Azure com subscription ativa
- Azure CLI (`az`) instalado e configurado
- kubectl 1.28+ instalado
- Helm 3.14+ instalado

Verifique os pre-requisitos:

```bash
az --version
# Esperado: azure-cli 2.x.x

az account show --query name -o tsv
# Esperado: Nome da sua subscription

az login
```

## Arquitetura Azure

```mermaid
graph TB
    subgraph VNET["VNet (10.0.0.0/16)"]
        subgraph AKS_Subnet["Subnet AKS"]
            subgraph AKS["AKS Cluster"]
                APPGW[Application Gateway<br/>HTTPS :443]
                BACKEND[Backend Pods x2-10<br/>:4003]
                ADMIN[Admin Pods x2-5<br/>:80]
            end
        end

        subgraph Data_Subnet["Subnet Dados"]
            PGFLEX[(Azure Database<br/>PostgreSQL Flexible Server)]
            CACHE[(Azure Cache<br/>for Redis Premium)]
        end

        subgraph NATS_Subnet["Subnet NATS"]
            NATS1[VM NATS 1]
            NATS2[VM NATS 2]
            NATS3[VM NATS 3]
        end
    end

    subgraph External["Servicos Azure"]
        ACR[Azure Container Registry]
        MONITOR[Azure Monitor]
        KV[Key Vault]
        DNS_ZONE[Azure DNS]
    end

    APPGW --> BACKEND
    APPGW --> ADMIN
    BACKEND --> PGFLEX
    BACKEND --> CACHE
    BACKEND --> NATS1
    AKS -.-> ACR
    BACKEND -.-> MONITOR
    AKS -.-> KV
```

## Passo 1: Criar Resource Group

```bash
az group create \
  --name monetarie-pix-rg \
  --location brazilsouth
```

Saida esperada:
```json
{
  "location": "brazilsouth",
  "name": "monetarie-pix-rg",
  "provisioningState": "Succeeded"
}
```

## Passo 2: Criar Cluster AKS

```bash
az aks create \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-aks \
  --location brazilsouth \
  --node-count 3 \
  --node-vm-size Standard_D4s_v5 \
  --enable-managed-identity \
  --enable-workload-identity \
  --enable-oidc-issuer \
  --network-plugin azure \
  --generate-ssh-keys \
  --enable-cluster-autoscaler \
  --min-count 2 \
  --max-count 6
```

Saida esperada (~10 minutos):
```
Running ..
Finished ..
```

Configurar kubectl:

```bash
az aks get-credentials \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-aks

kubectl get nodes
# Esperado: 3 nodes Ready
```

## Passo 3: Criar Azure Database for PostgreSQL

```bash
az postgres flexible-server create \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-db \
  --location brazilsouth \
  --version 16 \
  --sku-name Standard_D4s_v3 \
  --storage-size 128 \
  --admin-user postgres \
  --admin-password "<SENHA_SEGURA>" \
  --tier GeneralPurpose \
  --high-availability ZoneRedundant \
  --backup-retention 30 \
  --vnet monetarie-pix-vnet \
  --subnet data-subnet \
  --yes
```

Criar banco de dados:

```bash
az postgres flexible-server db create \
  --resource-group monetarie-pix-rg \
  --server-name monetarie-pix-db \
  --database-name monetarie

# Configurar parametros
az postgres flexible-server parameter set \
  --resource-group monetarie-pix-rg \
  --server-name monetarie-pix-db \
  --name max_connections \
  --value 3000

# Obter hostname
az postgres flexible-server show \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-db \
  --query fullyQualifiedDomainName -o tsv
# Esperado: monetarie-pix-db.postgres.database.azure.com
```

## Passo 4: Criar Azure Cache for Redis

```bash
az redis create \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-redis \
  --location brazilsouth \
  --sku Premium \
  --vm-size P1 \
  --enable-non-ssl-port \
  --replicas-per-master 1

# Obter hostname e chave de acesso
az redis show \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-redis \
  --query hostName -o tsv
# Esperado: monetarie-pix-redis.redis.cache.windows.net

az redis list-keys \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-redis \
  --query primaryKey -o tsv
```

## Passo 5: Configurar NATS em Azure VMs

```bash
for i in 1 2 3; do
  az vm create \
    --resource-group monetarie-pix-rg \
    --name nats-$i \
    --location brazilsouth \
    --image Ubuntu2404 \
    --size Standard_D2s_v5 \
    --admin-username azureuser \
    --generate-ssh-keys \
    --vnet-name monetarie-pix-vnet \
    --subnet nats-subnet \
    --nsg nats-nsg \
    --custom-data nats-cloud-init.yaml
done

# Abrir portas para NATS
az network nsg rule create \
  --resource-group monetarie-pix-rg \
  --nsg-name nats-nsg \
  --name AllowNATS \
  --access Allow \
  --direction Inbound \
  --priority 100 \
  --source-address-prefixes 10.0.0.0/16 \
  --destination-port-ranges 4222 6222 8222
```

## Passo 6: Configurar Azure Container Registry

```bash
# Criar ACR
az acr create \
  --resource-group monetarie-pix-rg \
  --name monetariepixacr \
  --sku Premium \
  --location brazilsouth

# Vincular ACR ao AKS
az aks update \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-aks \
  --attach-acr monetariepixacr

# Build e push (usando ACR Tasks para build remoto)
az acr build \
  --registry monetariepixacr \
  --image monetarie/pix-backend:latest \
  backend/

az acr build \
  --registry monetariepixacr \
  --image monetarie/pix-admin:latest \
  frontend/admin/
```

## Passo 7: Instalar Application Gateway Ingress Controller

```bash
# Habilitar AGIC addon
az aks enable-addons \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-aks \
  --addons ingress-appgw \
  --appgw-name monetarie-pix-appgw \
  --appgw-subnet-cidr "10.0.3.0/24"
```

## Passo 8: Criar Secrets no AKS

```bash
kubectl create namespace pix

# Secret do banco de dados
kubectl create secret generic db-credentials \
  --namespace pix \
  --from-literal=database-url="ecto://postgres:<SENHA>@monetarie-pix-db.postgres.database.azure.com:5432/monetarie?sslmode=require"

# Secret do PIX
kubectl create secret generic pix-secrets \
  --namespace pix \
  --from-literal=secret-key-base="$(openssl rand -base64 64 | tr -d '\n')"

# Secret JWT compartilhado
kubectl create secret generic monetarie-shared-jwt-secret \
  --namespace pix \
  --from-literal=secret="<GUARDIAN_SECRET_KEY>"
```

## Passo 9: Deploy com Helm

```bash
helm install monetarie-pix deploy/kubernetes/helm/pix \
  --namespace pix \
  -f deploy/kubernetes/helm/pix/values-azure.yaml \
  --set backend.image.repository=monetariepixacr.azurecr.io/monetarie/pix-backend \
  --set admin.image.repository=monetariepixacr.azurecr.io/monetarie/pix-admin \
  --set redis.host="monetarie-pix-redis.redis.cache.windows.net" \
  --set nats.host="<NATS_IP_1>" \
  --set "nats.cluster[0]=<NATS_IP_1>:4222" \
  --set "nats.cluster[1]=<NATS_IP_2>:4222" \
  --set "nats.cluster[2]=<NATS_IP_3>:4222"
```

## Passo 10: Migrations e Verificacao

```bash
# Migrations
kubectl exec -n pix deployment/monetarie-pix-backend -- \
  bin/monetarie_pix eval "Shared.Release.migrate()"

# Seeds
kubectl exec -n pix deployment/monetarie-pix-backend -- \
  bin/monetarie_pix eval "Shared.Release.seed()"

# Verificar pods
kubectl get pods -n pix

# Health check
curl -s https://pixapi.seudominio.com/health
# Esperado: {"status":"ok"}
```

## Azure Monitor

### Container Insights

O AKS integra nativamente com Azure Monitor Container Insights:

```bash
az aks enable-addons \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-aks \
  --addons monitoring
```

### Alertas Recomendados

| Alerta | Metrica | Threshold |
|--------|---------|-----------|
| DB CPU | PostgreSQL CPU Percent | > 80% |
| DB Storage | PostgreSQL Storage Percent | > 85% |
| Redis Memory | Azure Cache Used Memory | > 80% |
| Pod Restarts | Container Restart Count | > 5 em 5min |
| API Latencia | Request Duration P99 | > 2s |

### Metricas Prometheus

```bash
# Habilitar Azure Managed Prometheus
az aks update \
  --resource-group monetarie-pix-rg \
  --name monetarie-pix-aks \
  --enable-azure-monitor-metrics
```

## Resultado Esperado

Ao final deste guia, voce tera:

- Cluster AKS com 3 nodes em `brazilsouth` (Sao Paulo)
- Azure Database for PostgreSQL 16 Flexible Server com HA
- Azure Cache for Redis Premium com replica
- Cluster NATS de 3 VMs
- Azure Container Registry com imagens Monetarie PIX
- Application Gateway Ingress com TLS
- Monetarie PIX rodando com 2+ backend pods e 2+ admin pods
- Azure Monitor com Container Insights e alertas
