import { Inject, InternalServerErrorException } from '@nestjs/common';
// eslint-disable-next-line @typescript-eslint/consistent-type-imports -- NestJS DI requires value imports for emitDecoratorMetadata
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
// eslint-disable-next-line @typescript-eslint/consistent-type-imports -- NestJS DI requires value imports for emitDecoratorMetadata
import { DomainException, LoggerService } from '@modules/shared';
import {
  SAVED_LISTING_REPOSITORY,
  type ISavedListingRepository,
} from '../../../domain/repositories/saved-listing.repository';
import { RemoveFavoriteCommand } from './remove-favorite.command';

@CommandHandler(RemoveFavoriteCommand)
export class RemoveFavoriteHandler
  implements ICommandHandler<RemoveFavoriteCommand>
{
  constructor(
    @Inject(SAVED_LISTING_REPOSITORY)
    private readonly savedListingRepo: ISavedListingRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: RemoveFavoriteCommand): Promise<void> {
    try {
      await this.savedListingRepo.remove(command.userId, command.listingId);
      this.logger.log(
        `User ${command.userId} unfavorited listing ${command.listingId}`,
        'RemoveFavoriteHandler',
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to remove favorite: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'RemoveFavoriteHandler',
      );
      throw new InternalServerErrorException('Lỗi khi xóa yêu thích');
    }
  }
}
