import { EventsHandler, CommandBus, type IEventHandler } from '@nestjs/cqrs';
import { InquiryCreatedEvent } from '@modules/inquiries/domain/events/inquiry-created.event';
import { LoggerService, PrismaService } from '@modules/shared';
import { CreateLeadCommand } from '../commands/create-lead/create-lead.command';

/**
 * Listens for InquiryCreatedEvent (emitted via CQRS EventBus) and
 * automatically creates a Lead for the listing's agent.
 *
 * Source mapping:
 *   - agentUserId — resolved from listing.agent.user.id
 *   - name / phone — from the inquiring user's profile
 *   - source       — 'INQUIRY' (indicates lead came from a property inquiry)
 */
@EventsHandler(InquiryCreatedEvent)
export class InquiryCreatedToLeadListener implements IEventHandler<InquiryCreatedEvent> {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async handle(event: InquiryCreatedEvent): Promise<void> {
    try {
      const listing = await this.prisma.listing.findUnique({
        where: { id: event.listingId },
        include: {
          agent: { include: { user: { select: { id: true } } } },
        },
      });

      if (!listing?.agent?.user?.id) {
        this.logger.debug(
          `InquiryCreatedToLeadListener: listing ${event.listingId} has no agent — skipping lead creation`,
          'InquiryCreatedToLeadListener',
        );
        return;
      }

      const sender = await this.prisma.user.findUnique({
        where: { id: event.userId },
        select: { fullName: true, phone: true, email: true },
      });

      if (!sender) {
        this.logger.warn(
          `InquiryCreatedToLeadListener: sender ${event.userId} not found — skipping lead creation`,
          'InquiryCreatedToLeadListener',
        );
        return;
      }

      const name = sender.fullName ?? sender.phone ?? 'Khách hàng';
      const phone = sender.phone ?? '';
      const email = sender.email ?? null;

      await this.commandBus.execute(
        new CreateLeadCommand(
          listing.agent.user.id,
          name,
          phone,
          email,
          'INQUIRY',
          null,
          `Tự động tạo từ yêu cầu tư vấn #${event.aggregateId}`,
        ),
      );

      this.logger.log(
        `Lead created for agent ${listing.agent.user.id} from inquiry ${event.aggregateId}`,
        'InquiryCreatedToLeadListener',
      );
    } catch (error) {
      // Non-blocking — a lead creation failure must never break the inquiry flow
      this.logger.error(
        `Failed to auto-create lead from inquiry ${event.aggregateId}: ${
          error instanceof Error ? error.message : String(error)
        }`,
        error instanceof Error ? error.stack : undefined,
        'InquiryCreatedToLeadListener',
      );
    }
  }
}
