# Workflow Best Practices

This guide provides best practices and tips for creating effective Bangstack workflows.

## Table of Contents

- [Workflow Structure](#workflow-structure)
- [Naming Conventions](#naming-conventions)
- [Component Organization](#component-organization)
- [Validation and Testing](#validation-and-testing)
- [Version Management](#version-management)
- [Performance Tips](#performance-tips)
- [Common Patterns](#common-patterns)
- [Troubleshooting](#troubleshooting)

## Workflow Structure

### Start Simple, Iterate

Begin with a minimal viable workflow and expand incrementally:

```yaml
# ✓ Good - Start simple
workflow:
  id: task-api
  version: 1.0.0
  name: Task API
  description: Basic CRUD API for tasks

stack:
  api:
    type: backend
    technology: typescript/express
    endpoints:
      - id: list-tasks
        path: /api/tasks
        method: GET
```

### Use Descriptive IDs

IDs should be lowercase, hyphenated, and descriptive:

```yaml
# ✗ Bad
workflow:
  id: w1

stack:
  c1:
    endpoints:
      - id: ep1

# ✓ Good
workflow:
  id: user-authentication

stack:
  auth-api:
    endpoints:
      - id: login-endpoint
```

### Keep Related Components Together

Organize stack components logically:

```yaml
# ✓ Good - Logical grouping
stack:
  # Frontend
  web-app:
    type: frontend
    technology: react
    dependsOn: [api]

  # Backend
  api:
    type: backend
    technology: typescript/express
    dependsOn: [database]

  # Data layer
  database:
    type: database
    technology: postgresql
```

## Naming Conventions

### Component Names

Use clear, domain-specific names:

```yaml
# ✗ Bad - Generic names
stack:
  app:
    type: frontend
  server:
    type: backend

# ✓ Good - Descriptive names
stack:
  customer-portal:
    type: frontend
  payment-api:
    type: backend
```

### Endpoint IDs

Use action-noun format:

```yaml
# ✗ Bad
endpoints:
  - id: users
  - id: get
  - id: endpoint1

# ✓ Good
endpoints:
  - id: list-users
  - id: create-user
  - id: update-user
  - id: delete-user
```

### Database Tables

Use plural nouns:

```yaml
# ✗ Bad
tables:
  - name: user
  - name: task

# ✓ Good
tables:
  - name: users
  - name: tasks
  - name: order_items
```

## Component Organization

### Declare Dependencies

Always declare component dependencies explicitly:

```yaml
stack:
  api:
    type: backend
    dependsOn: [database, cache]  # ✓ Explicit dependencies

  web-app:
    type: frontend
    dependsOn: [api]  # ✓ Clear data flow

  database:
    type: database
    # No dependencies - base layer
```

### Use Expected Dependencies for Infrastructure

Track infrastructure service usage:

```yaml
stack:
  api:
    type: backend
    expected_dependencies:
      - service: redis
        usage: "Session storage and caching"
        required: true
      - service: queue
        usage: "Background job processing"
        required: false
```

This enables Bangstack to:
- Generate proper service clients
- Detect dependency mismatches
- Warn about drift between YAML and code

### Separate Concerns

Split complex systems into focused components:

```yaml
# ✓ Good - Separation of concerns
stack:
  auth-api:
    type: backend
    description: "Authentication and authorization"

  user-api:
    type: backend
    description: "User profile management"

  payment-api:
    type: backend
    description: "Payment processing"

# ✗ Bad - Everything in one component
stack:
  api:
    type: backend
    description: "All backend logic"
```

## Validation and Testing

### Validate Before Generating

Always validate your workflow before generation:

```bash
# Validate first
bang validate workflow.yaml

# Then generate
bang generate workflow.yaml
```

### Use Dry Run

Preview what will be generated:

```bash
bang generate workflow.yaml --dry-run --verbose
```

This shows:
- Number of files that will be generated
- Directory structure
- Any warnings or issues

### Define Test Scenarios

Include comprehensive test specifications:

```yaml
testing:
  unit_tests:
    - component: api.create-task
      scenarios:
        - creates task with valid data
        - validates required fields
        - returns 201 status code
        - handles duplicate tasks
        - validates field lengths

  integration_tests:
    - component: api
      scenarios:
        - complete CRUD workflow
        - handles database connection errors
        - validates authentication
```

### Test Generated Code

After generation, run tests immediately:

```bash
bang generate workflow.yaml
cd generated/api
npm install
npm test  # Verify generated tests pass
```

## Version Management

### Use Semantic Versioning

Follow semver (MAJOR.MINOR.PATCH):

```yaml
# ✓ Good
workflow:
  version: 1.0.0   # Initial release
  version: 1.1.0   # New feature (backward compatible)
  version: 2.0.0   # Breaking change

# ✗ Bad
workflow:
  version: v1      # Too vague
  version: latest  # Not semantic
```

### Create Versions for Major Changes

Use version management for significant changes:

```bash
# Before making infrastructure changes
bang version create 2.0.0 -m "Switch from Redis to Upstash"

# Update your workflow.yaml

# Generate with new version
bang generate workflow.yaml
```

### Verify After Rollback

Always verify after rolling back versions:

```bash
# Rollback to previous version
bang version rollback 1.0.0

# Verify the change
bang verify workflow.yaml -o ./src

# Regenerate if needed
bang generate workflow.yaml -o ./src
```

### Track Changes

Use descriptive version messages:

```bash
# ✓ Good - Descriptive
bang version create 2.1.0 -m "Add email notification service"
bang version create 3.0.0 -m "Migrate from MongoDB to PostgreSQL"

# ✗ Bad - Vague
bang version create 2.0.0 -m "Updates"
bang version create 2.1.0 -m "Changes"
```

## Performance Tips

### Use --verbose Sparingly

Only use verbose mode when debugging:

```bash
# For normal use
bang generate workflow.yaml

# For debugging
bang generate workflow.yaml --verbose
```

### Leverage Progress Indicators

Watch real-time progress during generation:

```bash
bang generate workflow.yaml
# ⠋ Writing Files (45/62) api/src/routes/tasks.ts
```

### Optimize Large Workflows

For large workflows (100+ files):

1. Split into multiple smaller workflows
2. Use file references for reusable components
3. Generate incrementally during development

### Use Dry Run for Large Changes

Test major changes without writing files:

```bash
bang generate workflow.yaml --dry-run > preview.txt
```

## Common Patterns

### API + Database

Standard backend pattern:

```yaml
stack:
  api:
    type: backend
    technology: typescript/express
    dependsOn: [database]
    endpoints:
      - id: create-item
        path: /api/items
        method: POST

  database:
    type: database
    technology: postgresql
    tables:
      - name: items
```

### Full-Stack Application

Frontend + Backend + Database:

```yaml
stack:
  web-app:
    type: frontend
    technology: react
    dependsOn: [api]

  api:
    type: backend
    technology: typescript/express
    dependsOn: [database]

  database:
    type: database
    technology: postgresql
```

### Microservices

Multiple backend services:

```yaml
stack:
  auth-service:
    type: backend
    technology: typescript/express
    dependsOn: [auth-db]

  user-service:
    type: backend
    technology: typescript/express
    dependsOn: [user-db]

  auth-db:
    type: database
    technology: postgresql

  user-db:
    type: database
    technology: postgresql
```

### CLI Tool

Command-line application:

```yaml
stack:
  cli:
    type: cli
    technology: typescript/node
    config:
      bin_name: my-tool
    commands:
      - id: init-command
        name: init
        description: Initialize a new project
```

## Troubleshooting

### Validation Errors

Read error messages carefully - they include examples:

```
✖ Validation errors in workflow.yaml:

1. workflow.version
   Error: Version is required
   → Use semantic versioning like "1.0.0"

   Example:
   ✗ version: ""
   ✓ version: 1.0.0
```

### Generator Not Found

Use list-generators to see available options:

```bash
bang list-generators --verbose
```

If you get "Generator not found", check:
1. Spelling (case-sensitive)
2. Technology format (e.g., `typescript/express` not `express`)
3. Available generators with `bang list`

### Dependency Mismatches

Use verify to detect drift:

```bash
bang verify workflow.yaml -o ./src
```

Fix mismatches by either:
1. Updating YAML to match code
2. Regenerating code to match YAML

### Generation Failures

If generation fails:

1. **Check validation**: `bang validate workflow.yaml`
2. **Try dry run**: `bang generate workflow.yaml --dry-run`
3. **Check disk space**: Ensure enough space for files
4. **Check permissions**: Verify write permissions on output directory
5. **Use verbose mode**: `bang generate workflow.yaml --verbose`

### Performance Issues

For slow generation:

1. Split large workflows into smaller ones
2. Use SSD for faster I/O
3. Close unnecessary applications
4. Check for disk space issues

## Advanced Patterns

### Reusable Components with $ref

Split large workflows into reusable files:

```yaml
# workflow.yaml
stack:
  api:
    type: backend
    endpoints:
      $ref: './endpoints/auth.yaml'

# endpoints/auth.yaml
- id: login-endpoint
  path: /api/auth/login
  method: POST
```

### Template Variables

Use variables for dynamic values:

```yaml
endpoints:
  - id: create-user
    payload:
      email: "{{ state.email }}"
      name: "{{ state.name }}"
```

### Multi-Environment Configuration

Define environment-specific configs:

```yaml
environment:
  development:
    API_URL: http://localhost:3000
    DEBUG: true

  production:
    API_URL: https://api.example.com
    DEBUG: false
```

## Summary Checklist

Before generating, ensure:

- [ ] IDs are lowercase and hyphenated
- [ ] Dependencies are explicitly declared
- [ ] Semantic versioning is used
- [ ] Workflow is validated (`bang validate`)
- [ ] Test scenarios are defined
- [ ] Infrastructure dependencies are tracked
- [ ] Component names are descriptive
- [ ] Documentation sections are included

After generating, verify:

- [ ] Generated tests pass
- [ ] No validation warnings (`bang verify`)
- [ ] File count matches expectations
- [ ] Dependencies installed successfully
- [ ] Application runs without errors

## Getting Help

- **Validation errors**: Read error messages - they include examples
- **Generator issues**: Run `bang list-generators --verbose`
- **Drift detection**: Use `bang verify workflow.yaml`
- **Examples**: Check `examples/` directory
- **Documentation**: See [WORKFLOW-SCHEMA.md](./WORKFLOW-SCHEMA.md)
- **Issues**: Report at https://github.com/mogullabs/bangstack/issues
