import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { type PaymentCompletedEvent } from '@modules/payments';
import { PrismaService, LoggerService, EventBusService } from '@modules/shared';

const PACKAGE_DURATION_DAYS: Record<string, { days: number; package_: string }> = {
  '99000': { days: 3, package_: '3_days' },
  '199000': { days: 7, package_: '7_days' },
  '499000': { days: 30, package_: '30_days' },
};

@Injectable()
export class ActivateFeaturedListingHandler {
  constructor(
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
    private readonly eventBus: EventBusService,
  ) {}

  @OnEvent('payment.completed', { async: true })
  async handle(event: PaymentCompletedEvent): Promise<void> {
    const payment = await this.prisma.payment.findUnique({
      where: { id: event.aggregateId },
      select: { type: true, transactionId: true, amountVND: true },
    });

    if (!payment || payment.type !== 'FEATURED_LISTING' || !payment.transactionId) {
      return;
    }

    const listingId = payment.transactionId;
    const pkg = PACKAGE_DURATION_DAYS[payment.amountVND.toString()] ?? { days: 7, package_: '7_days' };

    const now = new Date();
    const listing = await this.prisma.listing.findUnique({
      where: { id: listingId },
      select: { featuredUntil: true },
    });

    // Extend from current featuredUntil if still active, otherwise from now
    const baseDate = listing?.featuredUntil && listing.featuredUntil > now
      ? listing.featuredUntil
      : now;

    const featuredUntil = new Date(baseDate.getTime() + pkg.days * 24 * 60 * 60 * 1000);

    await this.prisma.listing.update({
      where: { id: listingId },
      data: { featuredUntil, featuredPackage: pkg.package_ },
    });

    // Trigger Typesense re-index so the listing gets featured boost in search
    this.eventBus.publish({ eventName: 'listing.updated', aggregateId: listingId, occurredAt: new Date() });

    this.logger.log(
      `Activated featured listing: id=${listingId}, package=${pkg.package_}, until=${featuredUntil.toISOString()}, days=${pkg.days}`,
      'ActivateFeaturedListingHandler',
    );
  }
}
