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 UserListResult } from '../../../domain/repositories/admin-query.repository';
import { GetUsersQuery } from './get-users.query';

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

  async execute(query: GetUsersQuery): Promise<UserListResult> {
    try {
      return await this.adminQueryRepo.getUsers({
        page: query.page,
        limit: query.limit,
        role: query.role,
        isActive: query.isActive,
        search: query.search,
      });
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get users: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetUsersHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy danh sách người dùng');
    }
  }
}
