{%- import "util.jinja.include" as util -%}
{%- import "cloudevents.jinja.include" as cloudEvents -%}
{%- set messagegroups = root.messagegroups %}
{% for messagegroupid, messagegroup in messagegroups.items() -%}
{%- set groupname = messagegroupid | pascal -%}
{%- set class_name = (project_name | pascal | strip_namespace) + "Function" %}
# {{ project_name | pascal }} - Azure Service Bus Function

Auto-generated Azure Function for processing Azure Service Bus messages.

## Overview

This Azure Function automatically triggers when messages arrive in your Service Bus queue or topic subscription. It deserializes messages and calls your custom handlers - perfect for building event-driven microservices!

## Quick Start

### 1. Configure Connection

**local.settings.json:**
```json
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ServiceBusConnectionString": "Endpoint=sb://YOUR-NAMESPACE.servicebus.windows.net/;SharedAccessKeyName=..."
  }
}
```

### 2. Add Your Logic

```csharp
{%- set first_message = messagegroup.messages.items() | first %}
{%- if first_message %}
{%- set messageid, message = first_message %}
{%- set messagename = messageid | pascal | strip_namespace %}
{%- set message_body_type = util.body_type(data_project_name, root, message) %}
protected async Task Handle{{ messagename }}Async(
    CloudEvent cloudEvent,
    {{ message_body_type }} data)
{
    _logger.LogInformation("Processing message: {EventId}", cloudEvent.Id);
    
    // TODO: Your business logic here
    await ProcessDataAsync(data);
}
{%- endif %}
```

### 3. Run Locally

```bash
func start
```

### 4. Deploy to Azure

```bash
func azure functionapp publish your-function-app-name
```

## Event Handlers

{% for messageid, message in messagegroup.messages.items() -%}
{%- set messagename = messageid | pascal | strip_namespace %}
{%- set message_body_type = util.body_type(data_project_name, root, message) %}
### Handle{{ messagename }}Async

**Message Type:** `{{ messageid }}`  
**Data Type:** `{{ message_body_type }}`

```csharp
protected async Task Handle{{ messagename }}Async(CloudEvent ce, {{ message_body_type }} data)
{
    // Your processing logic
}
```

{% endfor %}

## Message Completion

Messages are automatically completed (acknowledged) after successful processing. If your handler throws an exception, the message returns to the queue for retry.

### Configuring Retries

In `host.json`:
```json
{
  "extensions": {
    "serviceBus": {
      "prefetchCount": 100,
      "maxConcurrentCalls": 16,
      "maxAutoLockRenewalDuration": "00:05:00"
    }
  }
}
```

## Dead-Letter Queue

After maximum delivery attempts, messages go to the dead-letter queue. Create a separate function to process them:

```csharp
[Function("ProcessDeadLetterQueue")]
public async Task RunDeadLetter(
    [ServiceBusTrigger("your-queue/$DeadLetterQueue")] ServiceBusReceivedMessage message)
{
    _logger.LogWarning("Dead-lettered message: {Reason}", message.DeadLetterReason);
}
```

## Dependency Injection

In `Program.cs`:
```csharp
builder.Services.AddDbContext<MyDbContext>();
builder.Services.AddScoped<IMyService, MyService>();
```

Inject into function:
```csharp
private readonly IMyService _service;

public {{ class_name }}(ILoggerFactory loggerFactory, IMyService service)
    : base(loggerFactory)
{
    _service = service;
}
```

## Testing

```bash
dotnet test
```

## Learn More

- [Azure Functions Service Bus Trigger](https://learn.microsoft.com/azure/azure-functions/functions-bindings-service-bus-trigger)
- [xRegistry CLI Documentation](https://github.com/xregistry/codegen)

## Generated Code

Auto-generated by [xRegistry CLI](https://github.com/xregistry/codegen).

**Message Group:** {{ groupname }}  
**Trigger:** Azure Service Bus  
**Runtime:** Azure Functions
{% endfor %}
