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

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

  @OnEvent('listing.created', { async: true })
  async handle(event: ListingCreatedEvent): Promise<void> {
    this.logger.log(
      `Metering listings_created usage for seller=${event.sellerId}`,
      'ListingCreatedUsageHandler',
    );

    try {
      await this.commandBus.execute(
        new MeterUsageCommand(event.sellerId, 'listings_created', 1),
      );
    } catch (error) {
      // Log but don't fail — usage metering is best-effort
      // User without subscription still creates listing (quota check already passed in guard)
      this.logger.warn(
        `Failed to meter usage for seller=${event.sellerId}: ${(error as Error).message}`,
        'ListingCreatedUsageHandler',
      );
    }
  }
}
