import { InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { TrackEventCommand } from './track-event.command';

export interface TrackEventResult {
  tracked: boolean;
  eventType: string;
}

@CommandHandler(TrackEventCommand)
export class TrackEventHandler implements ICommandHandler<TrackEventCommand> {
  constructor(private readonly logger: LoggerService) {}

  async execute(command: TrackEventCommand): Promise<TrackEventResult> {
    try {
      this.logger.log(
        `Analytics event: ${command.eventType} on ${command.entityType}:${command.entityId}`,
        'TrackEventHandler',
      );

      return {
        tracked: true,
        eventType: command.eventType,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to ghi nhận sự kiện phân tích: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể ghi nhận sự kiện phân tích. Vui lòng thử lại sau.');
    }
  }
}
