import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import {
  AGENT_REPOSITORY,
  type AgentPublicProfileData,
  type IAgentRepository,
} from '../../../domain/repositories/agent.repository';
import { GetAgentPublicProfileQuery } from './get-agent-public-profile.query';

@QueryHandler(GetAgentPublicProfileQuery)
export class GetAgentPublicProfileHandler
  implements IQueryHandler<GetAgentPublicProfileQuery>
{
  constructor(
    @Inject(AGENT_REPOSITORY)
    private readonly agentRepo: IAgentRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(
    query: GetAgentPublicProfileQuery,
  ): Promise<AgentPublicProfileData | null> {
    try {
      return this.agentRepo.getPublicProfile(query.agentId);
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get agent public profile: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể tải hồ sơ công khai của môi giới');
    }
  }
}
