# CDP Edge - Setup CI/CD e Versionamento Automático

## Fluxo Escolhido

Escolha **UMA** das opções:

| Opção | Versão | Quando usar |
|-------|--------|------------|
| **semantic-release** | Automática | Commits convencionais, time pequeno |
| **Manual workflow** | Controlada | Quer aprovar cada release |

---

## PASSO 1: Criar Conta e Token no npm

```bash
# 1. Criar conta em https://www.npmjs.com/signup

# 2. Login
npm login

# 3. Criar token de automação
# Vá em: https://www.npmjs.com/settings/tokens
# - Clique "Create New Token"
# - Nome: "GitHub Actions"
# - Tipo: "Automation"
# - Copie o token gerado
```

---

## PASSO 2: Configurar Secrets no GitHub

Vá no repositório: `Settings` → `Secrets and variables` → `Actions` → `New repository secret`

**Adicione:**

| Nome | Valor |
|------|-------|
| `NPM_TOKEN` | Token do passo 1 |
| `GITHUB_TOKEN` | Já existe automaticamente (não precisa criar) |

---

## PASSO 3: Configurar o Workflow

### Opção A: semantic-release (Automática)

```bash
# 1. Adicionar dependências
npm install -D semantic-release @semantic-release/changelog @semantic-release/commit-analyzer @semantic-release/github @semantic-release/npm @semantic-release/release-notes-generator

# 2. O arquivo .releaserc.json já está criado
# 3. O workflow .github/workflows/release.yml já está criado
# 4. Commit e push
git add .
git commit -m "ci: add semantic-release automation"
git push
```

**Como usar:**

```bash
# Nova feature
git commit -m "feat: add Reddit support"

# Bugfix
git commit -m "fix: correct TikTok endpoint"

# Breaking change
git commit -m "feat!: remove GTM support"
# ou
git commit -m "feat: add new API

BREAKING CHANGE: requires Node 20+"
```

Ao fazer push no `main`, o release é automático!

---

### Opção B: Manual Workflow

```bash
# 1. O arquivo .github/workflows/publish.yml já está criado
# 2. Commit e push
git add .
git commit -m "ci: add manual publish workflow"
git push
```

**Como usar:**

1. Vá em: `Actions` → `Publish to npm`
2. Clique `Run workflow`
3. Escolha o tipo: `patch`, `minor` ou `major`
4. Clique `Run workflow`

---

## PASSO 4: Configurar Conventional Commits (Opcional mas recomendado)

```bash
# Instalar commitlint
npm install -D @commitlint/cli @commitlint/config-conventional

# Criar commitlint.config.js
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

# Adicionar ao package.json scripts
# "prepare": "husky install"
# "commitlint": "commitlint --edit"

# Instalar husky
npm install -D husky
npx husky install
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
```

Agora commits inválidos são bloqueados!

---

## Fluxo Completo de Desenvolvimento

```
Desenvolvimento
      ↓
git commit -m "feat: nova funcionalidade"
      ↓
git push origin main
      ↓
GitHub Actions detecta push
      ↓
    ┌─────────┐
    │ semantic-│  (se Opção A)
    │ release  │──→ Calcula versão
    └─────────┘
      ↓
    ┌─────────┐
    │  CI/CD  │──→ Build + Test
    └─────────┘
      ↓
    ┌─────────┐
    │ Publish │──→ npm publish
    │  npm    │
    └─────────┘
      ↓
    ┌─────────┐
    │GitHub   │──→ Criar Release
    │ Release │    + Changelog
    └─────────┘
```

---

## Verificação

```bash
# Ver releases criados
npm view cdp-edge versions

# Ver changelog
# Vá em: https://github.com/seu-usuario/cdp-edge/releases
```

---

## Solução de Problemas

### Erro: "401 Unauthorized"
→ Verifique se `NPM_TOKEN` está correto no GitHub Secrets

### Erro: "403 Forbidden"
→ Verifique se o nome do pacote está disponível no npm

### Release não aparece
→ Verifique se o workflow falhou em `Actions`

---

## Dicas Avançadas

### Pre-release (beta, alpha)

```bash
git commit -m "feat: add beta feature

Release: 1.1.0-beta.1"
```

### Ignorar commits no release

```
# .releaserc.json
{
  "branches": ["main"],
  "tagFormat": "v${version}",
  "plugins": [
    "@semantic-release/commit-analyzer",
    {
      "preset": "conventionalcommits",
      "releaseRules": [
        { "type": "chore", "scope": "deps", "release": "patch" }
      ]
    }
  ]
}
```

### Multiple publish channels

Use scopes para diferentes canais:
```bash
npm publish --tag beta    # @beta
npm publish --tag next    # @next
```
