import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, NotFoundException, LoggerService } from '@modules/shared';
import {
  AGENT_REPOSITORY,
  type AgentDashboardData,
  type IAgentRepository,
} from '../../../domain/repositories/agent.repository';
import { GetAgentDashboardQuery } from './get-agent-dashboard.query';

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

  async execute(query: GetAgentDashboardQuery): Promise<AgentDashboardData> {
    try {
      const agent = await this.agentRepo.findByUserId(query.userId);
      if (!agent) {
        throw new NotFoundException('Không tìm thấy thông tin môi giới');
      }

      return this.agentRepo.getDashboard(agent.id);
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get agent dashboard: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể tải bảng điều khiển môi giới');
    }
  }
}
