"use strict";
/**
 * Event Types Generator
 * Generates TypeScript type interfaces from YAML event definitions
 */
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.generateEventTypes = generateEventTypes;
const path = __importStar(require("path"));
async function generateEventTypes(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 };
    }
    // Determine output directory based on backend technology
    const backendDir = workflow.technology?.backend?.directory || 'backend';
    const outputPath = path.join(context.outputDirectory, backendDir, 'src', 'types', 'events.ts');
    // Generate TypeScript event type interfaces
    const eventInterfaces = generateEventInterfaces(workflow);
    const eventPayloadTypes = generateEventPayloadTypes(workflow);
    const eventTypeUnion = generateEventTypeUnion(workflow);
    const eventRegistry = generateEventRegistry(workflow);
    const content = `/**
 * Event Type Definitions
 * Auto-generated from workflow events
 * DO NOT EDIT MANUALLY
 */

// ============================================================================
// Event Payload Type Mapping
// ============================================================================

${eventPayloadTypes}

// ============================================================================
// Event Interfaces
// ============================================================================

${eventInterfaces}

// ============================================================================
// Event Type Union
// ============================================================================

${eventTypeUnion}

// ============================================================================
// Event Registry (for runtime validation)
// ============================================================================

${eventRegistry}

// ============================================================================
// Type Guards
// ============================================================================

export function isValidEventType(eventType: string): eventType is EventType {
  return EVENT_REGISTRY.hasOwnProperty(eventType);
}

export function validateEventPayload<T extends EventType>(
  eventType: T,
  payload: unknown
): payload is EventPayloadMap[T] {
  // Basic runtime validation - can be extended with more sophisticated checks
  const eventDef = EVENT_REGISTRY[eventType];
  if (!eventDef) return false;

  if (typeof payload !== 'object' || payload === null) return false;

  const payloadObj = payload as Record<string, unknown>;
  const requiredFields = Object.keys(eventDef.payload);

  // Check all required fields exist
  for (const field of requiredFields) {
    if (!(field in payloadObj)) return false;
  }

  return true;
}
`;
    files.push({ path: outputPath, content });
    return { files };
}
/**
 * Generate TypeScript type mapping for event payloads
 */
function generateEventPayloadTypes(workflow) {
    const typeMapping = {
        string: 'string',
        number: 'number',
        boolean: 'boolean',
        array: 'unknown[]',
        object: 'Record<string, unknown>',
        date: 'Date | string',
    };
    const payloadTypes = [];
    Object.entries(workflow.events).forEach(([eventName, eventDef]) => {
        const fields = Object.entries(eventDef.payload)
            .map(([fieldName, fieldType]) => {
            const tsType = typeMapping[fieldType] || 'unknown';
            return `  ${fieldName}: ${tsType};`;
        })
            .join('\n');
        payloadTypes.push(`export interface ${toPascalCase(eventName)}Payload {
${fields}
}`);
    });
    return payloadTypes.join('\n\n');
}
/**
 * Generate event interfaces with metadata
 */
function generateEventInterfaces(workflow) {
    const interfaces = [];
    Object.entries(workflow.events).forEach(([eventName, eventDef]) => {
        const payloadType = `${toPascalCase(eventName)}Payload`;
        interfaces.push(`/**
 * ${eventDef.description}
 */
export interface ${toPascalCase(eventName)}Event {
  type: '${eventName}';
  payload: ${payloadType};
  timestamp: Date | string;
  correlationId?: string;
  userId?: string;
}`);
    });
    return interfaces.join('\n\n');
}
/**
 * Generate union type of all event types
 */
function generateEventTypeUnion(workflow) {
    const eventNames = Object.keys(workflow.events);
    const eventTypes = eventNames.map(name => `${toPascalCase(name)}Event`).join(' | ');
    return `export type Event = ${eventTypes};

export type EventType = ${eventNames.map(name => `'${name}'`).join(' | ')};

export type EventPayloadMap = {
${eventNames.map(name => `  '${name}': ${toPascalCase(name)}Payload;`).join('\n')}
};`;
}
/**
 * Generate event registry for runtime validation
 */
function generateEventRegistry(workflow) {
    const entries = Object.entries(workflow.events)
        .map(([eventName, eventDef]) => {
        const payloadFields = Object.entries(eventDef.payload)
            .map(([field, type]) => `      ${field}: '${type}'`)
            .join(',\n');
        return `  '${eventName}': {
    description: '${eventDef.description}',
    payload: {
${payloadFields}
    }
  }`;
    })
        .join(',\n');
    return `export const EVENT_REGISTRY = {
${entries}
} as const;`;
}
/**
 * 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-types-generator.js.map