import { Injectable } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { OnEvent } from '@nestjs/event-emitter';
import { type SavedSearchCreatedEvent } from '@modules/search';
import { LoggerService } from '@modules/shared';
import { MeterUsageCommand } from '../../application/commands/meter-usage/meter-usage.command';

@Injectable()
export class SavedSearchCreatedUsageHandler {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly logger: LoggerService,
  ) {}

  @OnEvent('saved-search.created', { async: true })
  async handle(event: SavedSearchCreatedEvent): Promise<void> {
    this.logger.log(
      `Metering searches_saved usage for user=${event.userId}`,
      'SavedSearchCreatedUsageHandler',
    );

    try {
      await this.commandBus.execute(
        new MeterUsageCommand(event.userId, 'searches_saved', 1),
      );
    } catch (error) {
      // Log but don't fail — usage metering is best-effort (quota already enforced by guard)
      this.logger.warn(
        `Failed to meter usage for user=${event.userId}: ${(error as Error).message}`,
        'SavedSearchCreatedUsageHandler',
      );
    }
  }
}
