{%- import "util.jinja.include" as util -%}
// This code was generated by the xRegistry tool.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.

import { EventHubConsumerClient, ReceivedEventData, SubscriptionEventHandlers } from '@azure/event-hubs';
import { ContainerClient } from '@azure/storage-blob';

/**
 * A wrapper for the Azure Event Hubs consumer that processes events
 */
export class EventHubsProcessor {
    private client: EventHubConsumerClient;
    private subscription: ReturnType<EventHubConsumerClient['subscribe']> | null = null;
    
    /**
     * Event handler for processing events
     */
    public processEvent?: (eventData: ReceivedEventData) => Promise<void>;
    
    /**
     * Event handler for errors
     */
    public processError?: (error: Error) => Promise<void>;
    
    /**
     * Create a new EventHubsProcessor
     * @param client The Azure Event Hubs consumer client
     */
    constructor(client: EventHubConsumerClient) {
        this.client = client;
    }
    
    /**
     * Start processing events
     * @param consumerGroup The consumer group name (default: "$Default")
     */
    async start(consumerGroup: string = '$Default'): Promise<void> {
        const handlers: SubscriptionEventHandlers = {
            processEvents: async (events: ReceivedEventData[]) => {
                for (const event of events) {
                    try {
                        if (this.processEvent) {
                            await this.processEvent(event);
                        }
                    } catch (error) {
                        console.error('Error processing event:', error);
                        if (this.processError && error instanceof Error) {
                            await this.processError(error);
                        }
                    }
                }
            },
            processError: async (error: Error) => {
                console.error('Event Hubs error:', error);
                if (this.processError) {
                    await this.processError(error);
                }
            }
        };
        
        this.subscription = this.client.subscribe(handlers);
    }
    
    /**
     * Stop processing events
     */
    async stop(): Promise<void> {
        if (this.subscription) {
            await this.subscription.close();
            this.subscription = null;
        }
        await this.client.close();
    }
}
