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 FavoriteItem,
  type ISavedListingRepository,
} from '../../../domain/repositories/saved-listing.repository';
import { ListFavoritesQuery } from './list-favorites.query';

export interface ListFavoritesResult {
  data: FavoriteItem[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

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

  async execute(query: ListFavoritesQuery): Promise<ListFavoritesResult> {
    try {
      const page = Math.max(query.page, 1);
      const limit = Math.min(Math.max(query.limit, 1), 100);
      const { data, total } = await this.savedListingRepo.listByUser(
        query.userId,
        { page, limit },
      );
      return {
        data,
        total,
        page,
        limit,
        totalPages: limit > 0 ? Math.ceil(total / limit) : 0,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to list favorites: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'ListFavoritesHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy danh sách yêu thích');
    }
  }
}
