# OCI API Gateway - Configuração para MFEs

## Visão Geral

Este documento detalha como configurar o OCI API Gateway para servir Micro Frontends (MFEs) via Object Storage.

## Arquitetura

```
┌─────────────────┐      ┌──────────────────┐      ┌─────────────────┐
│   Usuário       │ ───► │  API Gateway     │ ───► │  Object Storage │
│  (navegador)    │      │  (URL pública)   │      │  (PAR URL)      │
└─────────────────┘      └──────────────────┘      └─────────────────┘
```

## Fluxo Completo

### 1. Criar Bucket no Object Storage

```bash
# Via OCI CLI
oci os bucket create \
  --namespace-name "grbb7qzeuoag" \
  --name "mfe-user-dev" \
  --compartment-id "ocid1.compartment.oc1..xxx" \
  --storage-tier "Standard"
```

### 2. Fazer Upload dos Arquivos

```bash
# Upload via OCI CLI
cd dist/mfe-user/browser/

find . -type f | while read file; do
  oci os object put \
    --namespace-name "grbb7qzeuoag" \
    --bucket-name "nexus-mfe-user-dev" \
    --file "$file" \
    --object-name "${file#./}" \
    --content-type auto
done
```

### 3. Criar Pre-Authenticated Request (PAR)

```bash
# Criar PAR para acesso público
oci os preauth-request create \
  --namespace-name "grbb7qzeuoag" \
  --bucket-name "nexus-mfe-user-dev" \
  --name "mfe-user-par" \
  --access-type "ObjectRead" \
  --time-expiry 31536000
```

### 4. Criar API Gateway

```bash
# Verificar/criar subnet
oci network subnet list \
  --compartment-id "compartment-ocid" \
  --vcn-id "vcn-ocid"

# Criar API Gateway
oci api-gateway gateway create \
  --compartment-id "compartment-ocid" \
  --display-name "nexus-mfe-user-gateway" \
  --subnet-id "subnet-ocid" \
  --endpoint-type "PUBLIC"
```

### 5. Criar Deployment com Rotas

O deployment precisa de rotas específicas para SPAs (Angular):

```yaml
routes:
  # Rota principal - tudo para index.html (SPA)
  - path: /{req.*}
    methods: [GET]
    backend:
      type: HTTP
      url: "${PAR_URL}/${request.path[req]}"

  # Arquivos estáticos específicos
  - path: /{ext}.js
    methods: [GET]
    backend:
      type: HTTP
      url: "https://grbb7qzeuoag.objectstorage.sa-saopaulo-1.oci.customer-oci.com/n/grbb7qzeuoag/b/nexus-mfe-user-dev/o/${request.path[req]}"

  - path: /{ext}.css
    methods: [GET]
    backend:
      type: HTTP
      url: "https://grbb7qzeuoag.objectstorage.sa-saopaulo-1.oci.customer-oci.com/n/grbb7qzeuoag/b/nexus-mfe-user-dev/o/${request.path[req]}"
```

## Configuracao via Terraform (Implementado)

O API Gateway MFE e provisionado via Terraform no repositorio `tf_oci_clusters`.

### Repositorio: `tf_oci_clusters`

```
tf_oci_clusters/
├── modules/
│   ├── api_gateway_mfe/       # Modulo API Gateway MFE
│   │   ├── main.tf            # Gateway + Deployment (rotas SPA)
│   │   ├── variables.tf       # Inputs
│   │   ├── outputs.tf         # gateway_id, ip, hostname, endpoints
│   │   └── versions.tf        # oracle/oci ~> 7.0
│   └── network/
│       └── main.tf            # Subnet sbn-api-gateway (condicional)
├── environments/
│   └── dev/
│       ├── main.tf            # enable_api_gateway_subnet
│       ├── api_gateway_mfe.tf # Integracao do modulo
│       └── terraform.ci.tfvars # enable_api_gateway_mfe = true
```

### Uso do modulo

```hcl
# environments/dev/api_gateway_mfe.tf
module "api_gateway_mfe" {
  count          = var.enable_api_gateway_mfe ? 1 : 0
  source         = "../../modules/api_gateway_mfe"
  compartment_id = local.compartment_id
  subnet_id      = module.network.api_gateway_subnet_id
  env_name       = var.env_name
  display_name   = "api-gateway-mfe"

  mfe_deployments = [
    {
      name             = "mfe-user"
      bucket_name      = "nexus-mfe-user-development"
      region           = "sa-saopaulo-1"
      object_namespace = var.mfe_object_namespace  # grbb7qzeuoag
    },
    # Adicionar mais MFEs aqui:
    # { name = "mfe-shell", bucket_name = "nexus-mfe-shell-development", ... },
    # { name = "mfe-auth",  bucket_name = "nexus-mfe-auth-development",  ... },
  ]
}
```

### Rotas SPA (Angular)

O deployment cria duas rotas para cada MFE:

1. **`/`** (GET) -> `index.html` no Object Storage (SPA entry point)
2. **`/{path*}`** (GET) -> arquivos estaticos no Object Storage (JS, CSS, assets)

### Pipeline CI/CD

```
Push to main (tf_oci_clusters)
  -> Bootstrap (init + validate)
    -> Detect Changes (diff por environment)
      -> Plan (terraform plan -var-file=terraform.ci.tfvars)
        -> Manual Approval
          -> Apply (terraform apply)
```

Pipeline: `terraform-tf_oci_clusters` (ID 51)
Variable Group: `oci-terraform` (ID 34)

## URLs de Acesso

### DEV

| Tipo | URL |
|------|-----|
| API Gateway (privado) | `https://guhal72tzyekzchzamhhi3lvgi.apigateway.sa-saopaulo-1.oci.customer-oci.com/` |
| Planejado (publico) | `https://mfe-user-dev.invista.com.br` (pendente) |

## Troubleshooting

### Problema: Arquivos não carregam

1. Verificar se PAR está ativa
2. Verificar tipos de conteúdo (content-type)
3. Verificar rotas no deployment

### Problema: SPA routing não funciona

1. Garantir rota catch-all `/{req.*}` 
2. Backend deve resolver para index.html

### Problema: 403 Forbidden

1. Verificar se PAR não expirou
2. Verificar se bucket está público ou PAR está válida

## Comandos Úteis

```bash
# Listar API Gateways
oci api-gateway gateway list --compartment-id <compartment-id>

# Ver deployment
oci api-gateway deployment get --deployment-id <deployment-id>

# Atualizar deployment
oci api-gateway deployment update \
  --deployment-id <deployment-id> \
  --spec file://deployment-spec.yaml

# Listar PARs
oci os preauth-request list \
  --namespace-name "grbb7qzeuoag" \
  --bucket-name "nexus-mfe-user-dev"

# Deletar PAR
oci os preauth-request delete \
  --namespace-name "grbb7qzeuoag" \
  --bucket-name "nexus-mfe-user-dev" \
  --par-id <par-id>
```

## Referências

- [OCI API Gateway Docs](https://docs.oracle.com/en-us/iaas/Content/APIGateway/apigateway.htm)
- [Static Website Hosting](https://docs.oracle.com/en/learn/oci-api-gateway-web-hosting/index.html)

---

*Atualizado em: 2026-02-23*
