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 { AddFavoriteCommand } from './add-favorite.command';

export interface AddFavoriteResult {
  id: string;
  listingId: string;
  createdAt: string;
}

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

  async execute(command: AddFavoriteCommand): Promise<AddFavoriteResult> {
    try {
      const saved = await this.savedListingRepo.add(
        command.userId,
        command.listingId,
      );
      this.logger.log(
        `User ${command.userId} favorited listing ${command.listingId}`,
        'AddFavoriteHandler',
      );
      return {
        id: saved.id,
        listingId: command.listingId,
        createdAt: saved.createdAt.toISOString(),
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to add favorite: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'AddFavoriteHandler',
      );
      throw new InternalServerErrorException('Lỗi khi thêm yêu thích');
    }
  }
}
