import { Inject, InternalServerErrorException } from '@nestjs/common';
// eslint-disable-next-line @typescript-eslint/consistent-type-imports -- NestJS DI requires value imports for emitDecoratorMetadata
import { IQueryHandler, QueryHandler } 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 { IsFavoritedQuery } from './is-favorited.query';

export interface IsFavoritedResult {
  favorited: boolean;
}

@QueryHandler(IsFavoritedQuery)
export class IsFavoritedHandler implements IQueryHandler<IsFavoritedQuery> {
  constructor(
    @Inject(SAVED_LISTING_REPOSITORY)
    private readonly savedListingRepo: ISavedListingRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: IsFavoritedQuery): Promise<IsFavoritedResult> {
    try {
      const favorited = await this.savedListingRepo.exists(
        query.userId,
        query.listingId,
      );
      return { favorited };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to check favorite status: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'IsFavoritedHandler',
      );
      throw new InternalServerErrorException('Lỗi khi kiểm tra yêu thích');
    }
  }
}
