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

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

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

  @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 days = PACKAGE_DURATION_DAYS[payment.amountVND.toString()] ?? 7;

    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() + days * 24 * 60 * 60 * 1000);

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

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