{%- 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 { Consumer, Kafka, EachMessagePayload } from 'kafkajs';
import { Logger, createLogger } from './logger.js';

/**
 * A simple wrapper for the KafkaJS consumer that processes messages
 */
export class KafkaProcessor {
    private consumer: Consumer;
    private running: boolean = false;
    private topicName: string;
    private logger: Logger;
    
    /**
     * Event handler for processing messages
     */
    public processMessage?: (payload: EachMessagePayload) => Promise<void>;
    
    /**
     * Event handler for errors
     */
    public processError?: (error: Error) => Promise<void>;
    
    /**
     * Create a new KafkaProcessor
     * @param consumer The KafkaJS consumer instance
     * @param topicName The topic to subscribe to
     * @param logger Optional logger instance
     */
    constructor(consumer: Consumer, topicName: string, logger?: Logger) {
        this.consumer = consumer;
        this.topicName = topicName;
        this.logger = logger ?? createLogger({ component: 'KafkaProcessor' });
    }
    
    /**
     * Start processing messages
     */
    async start(): Promise<void> {
        if (this.running) {
            throw new Error('KafkaProcessor is already running');
        }
        
        this.running = true;
        this.logger.info('Starting Kafka processor', { topic: this.topicName });
        
        await this.consumer.connect();
        await this.consumer.subscribe({ topic: this.topicName, fromBeginning: true });
        
        await this.consumer.run({
            eachMessage: async (payload: EachMessagePayload) => {
                try {
                    if (this.processMessage) {
                        await this.processMessage(payload);
                    }
                } catch (error) {
                    this.logger.error('Error processing message', error as Error, {
                        topic: payload.topic,
                        partition: payload.partition,
                        offset: payload.message.offset
                    });
                    if (this.processError && error instanceof Error) {
                        await this.processError(error);
                    }
                }
            }
        });
    }
    
    /**
     * Stop processing messages
     */
    async stop(): Promise<void> {
        if (!this.running) {
            return;
        }
        
        this.logger.info('Stopping Kafka processor');
        this.running = false;
        await this.consumer.disconnect();
    }
}
