"use strict";
/**
 * Event Handlers Generator
 * Generates event handler implementations for consuming services
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateEventHandlers = generateEventHandlers;
const path = __importStar(require("path"));
async function generateEventHandlers(context) {
    const files = [];
    const workflow = context.extendedWorkflow;
    // Skip if no extended workflow or no events defined
    if (!workflow?.events || Object.keys(workflow.events).length === 0) {
        return { files };
    }
    // Skip if no Redis cache configured
    if (!workflow.technology?.cache || !workflow.technology.cache.provider.includes('redis')) {
        return { files };
    }
    const backendDir = workflow.technology?.backend?.directory || 'backend';
    // Generate handler files for each event
    Object.entries(workflow.events).forEach(([eventName, eventDef]) => {
        files.push(generateEventHandler(backendDir, context.outputDirectory, eventName, eventDef));
    });
    // Generate handlers index file
    files.push(generateHandlersIndex(backendDir, context.outputDirectory, workflow));
    // Generate subscriber initialization file
    files.push(generateSubscriberInitializer(backendDir, context.outputDirectory, workflow));
    return { files };
}
/**
 * Generate handler file for a specific event
 */
function generateEventHandler(backendDir, outputDirectory, eventName, eventDef) {
    const handlerName = toPascalCase(eventName) + 'Handler';
    const eventTypeName = toPascalCase(eventName) + 'Event';
    const content = `/**
 * ${eventDef.description}
 * Event Handler
 * DO NOT EDIT MANUALLY - Modify logic inside handleEvent function
 */

import { ${eventTypeName} } from '../types/events';

/**
 * Handle ${eventName} event
 */
export async function handle${handlerName}(event: ${eventTypeName}): Promise<void> {
  console.log('[${handlerName}] Processing event:', {
    type: event.type,
    correlationId: event.correlationId,
    userId: event.userId,
    timestamp: event.timestamp,
  });

  try {
    // TODO: Implement your business logic here
    // Example: Update related records, send notifications, trigger workflows, etc.

    // Access the event payload
    const payload = event.payload;

    // Example: Log the payload
    console.log('[${handlerName}] Payload:', payload);

    // Add your implementation here
    // Examples:
    // - await sendNotification(payload);
    // - await updateRelatedRecords(payload);
    // - await triggerWorkflow(payload);

    console.log('[${handlerName}] Event processed successfully');
  } catch (error) {
    console.error('[${handlerName}] Error processing event:', error);
    // Consider implementing retry logic or dead letter queue
    throw error;
  }
}
`;
    return {
        path: path.join(outputDirectory, backendDir, 'src', 'events', 'handlers', `${eventName}-handler.ts`),
        content,
    };
}
/**
 * Generate index file that exports all handlers
 */
function generateHandlersIndex(backendDir, outputDirectory, workflow) {
    const eventNames = Object.keys(workflow.events);
    const imports = eventNames
        .map(eventName => {
        const handlerName = toPascalCase(eventName) + 'Handler';
        return `export { handle${handlerName} } from './${eventName}-handler';`;
    })
        .join('\n');
    const content = `/**
 * Event Handlers Index
 * Exports all event handlers
 * DO NOT EDIT MANUALLY
 */

${imports}
`;
    return {
        path: path.join(outputDirectory, backendDir, 'src', 'events', 'handlers', 'index.ts'),
        content,
    };
}
/**
 * Generate subscriber initializer that wires up all handlers
 */
function generateSubscriberInitializer(backendDir, outputDirectory, workflow) {
    const eventNames = Object.keys(workflow.events);
    const imports = eventNames
        .map(eventName => {
        const handlerName = toPascalCase(eventName) + 'Handler';
        return `import { handle${handlerName} } from './handlers/${eventName}-handler';`;
    })
        .join('\n');
    const subscriptions = eventNames
        .map(eventName => {
        const handlerName = toPascalCase(eventName) + 'Handler';
        return `  {
    eventType: '${eventName}',
    handler: async (event) => await handle${handlerName}(event as any),
    name: '${handlerName}',
  }`;
    })
        .join(',\n');
    const content = `/**
 * Event Subscriber Initializer
 * Wires up all event handlers to the event bus
 * DO NOT EDIT MANUALLY
 */

import { initializeEventSubscribers, SubscriberConfig } from './event-subscriber';
import { EventType } from '../types/events';
${imports}

/**
 * Get all subscriber configurations
 */
export function getSubscriberConfigs(): SubscriberConfig[] {
  return [
${subscriptions}
  ];
}

/**
 * Initialize all event subscribers
 * Call this on application startup
 */
export async function initializeAllSubscribers(): Promise<void> {
  const configs = getSubscriberConfigs();
  await initializeEventSubscribers(configs);
  console.log(\`[Subscribers] Initialized \${configs.length} event subscribers\`);
}
`;
    return {
        path: path.join(outputDirectory, backendDir, 'src', 'events', 'subscriber-initializer.ts'),
        content,
    };
}
/**
 * Convert snake_case or kebab-case to PascalCase
 */
function toPascalCase(str) {
    return str
        .split(/[-_]/)
        .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
        .join('');
}
//# sourceMappingURL=event-handlers-generator.js.map