import { Injectable } from '@nestjs/common';

export interface WebhookCommand {
  slug: string;
  name: string;
  description: string;
  inputSchema: Record<string, unknown>;
  handler: (
    params: Record<string, unknown>,
    context?: Record<string, unknown>,
  ) => Promise<unknown>;
}

@Injectable()
export class WebhookCommandRegistry {
  private readonly commands = new Map<string, WebhookCommand>();

  register(command: WebhookCommand): void {
    this.commands.set(command.slug, command);
  }

  find(slug: string): WebhookCommand | undefined {
    return this.commands.get(slug);
  }

  list(): WebhookCommand[] {
    return Array.from(this.commands.values());
  }

  async dispatch(
    slug: string,
    params: Record<string, unknown>,
    context?: Record<string, unknown>,
  ): Promise<unknown> {
    const command = this.find(slug);
    if (!command) {
      throw new Error(`Unknown app_command slug: ${slug}`);
    }

    return command.handler(params, context);
  }
}
