import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { ADMIN_QUERY_REPOSITORY, type IAdminQueryRepository, type DashboardStats } from '../../../domain/repositories/admin-query.repository';
import { GetDashboardStatsQuery } from './get-dashboard-stats.query';

@QueryHandler(GetDashboardStatsQuery)
export class GetDashboardStatsHandler implements IQueryHandler<GetDashboardStatsQuery> {
  constructor(
    @Inject(ADMIN_QUERY_REPOSITORY) private readonly adminQueryRepo: IAdminQueryRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(_query: GetDashboardStatsQuery): Promise<DashboardStats> {
    try {
      return await this.adminQueryRepo.getDashboardStats();
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get dashboard stats: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetDashboardStatsHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy thống kê dashboard');
    }
  }
}
