import { Inject } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { NotFoundException, CacheService, CachePrefix, CacheTTL } from '@modules/shared';
import { type ListingDetailData } from '../../../domain/repositories/listing-read.dto';
import { LISTING_REPOSITORY, type IListingRepository } from '../../../domain/repositories/listing.repository';
import { GetListingQuery } from './get-listing.query';

/** @deprecated Use ListingDetailData from listing-read.dto instead */
export type ListingDetailDto = ListingDetailData;

@QueryHandler(GetListingQuery)
export class GetListingHandler implements IQueryHandler<GetListingQuery> {
  constructor(
    @Inject(LISTING_REPOSITORY) private readonly listingRepo: IListingRepository,
    private readonly cache: CacheService,
  ) {}

  async execute(query: GetListingQuery): Promise<ListingDetailData> {
    const cacheKey = CacheService.buildKey(CachePrefix.LISTING, query.listingId);

    return this.cache.getOrSet(
      cacheKey,
      async () => {
        const result = await this.listingRepo.findByIdWithProperty(query.listingId);
        if (!result) {
          throw new NotFoundException('Listing', query.listingId);
        }
        return result;
      },
      CacheTTL.LISTING_DETAIL,
      'listing',
    );
  }
}
