import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, NotFoundException, LoggerService } from '@modules/shared';
import { ADMIN_QUERY_REPOSITORY, type IAdminQueryRepository, type UserDetail } from '../../../domain/repositories/admin-query.repository';
import { GetUserDetailQuery } from './get-user-detail.query';

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

  async execute(query: GetUserDetailQuery): Promise<UserDetail> {
    try {
      const user = await this.adminQueryRepo.getUserDetail(query.userId);
      if (!user) {
        throw new NotFoundException('Người dùng không tồn tại');
      }
      return user;
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get user detail for ${query.userId}: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetUserDetailHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy thông tin người dùng');
    }
  }
}
