import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { PrismaService, DomainException, LoggerService } from '@modules/shared';
import { GetAgentByUserIdQuery } from './get-agent-by-user-id.query';

export interface AgentDto {
  id: string;
  userId: string;
  licenseNumber: string | null;
  agency: string | null;
  qualityScore: number;
  totalDeals: number;
  responseTimeAvg: number | null;
  bio: string | null;
  serviceAreas: unknown;
  isVerified: boolean;
  createdAt: Date;
}

@Injectable()
@QueryHandler(GetAgentByUserIdQuery)
export class GetAgentByUserIdHandler implements IQueryHandler<GetAgentByUserIdQuery> {
  constructor(
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetAgentByUserIdQuery): Promise<AgentDto | null> {
    try {
      const agent = await this.prisma.agent.findUnique({
        where: { userId: query.userId },
      });

      if (!agent) return null;

      return {
        id: agent.id,
        userId: agent.userId,
        licenseNumber: agent.licenseNumber,
        agency: agent.agency,
        qualityScore: agent.qualityScore,
        totalDeals: agent.totalDeals,
        responseTimeAvg: agent.responseTimeAvg,
        bio: agent.bio,
        serviceAreas: agent.serviceAreas,
        isVerified: agent.isVerified,
        createdAt: agent.createdAt,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get agent by user ID: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể lấy thông tin đại lý');
    }
  }
}
