import { PaymentCompletedEvent } from '@modules/payments/domain/events/payment-completed.event';
import type { SendNotificationCommand } from '../commands/send-notification/send-notification.command';
import { PaymentCompletedListener } from '../listeners/payment-completed.listener';

describe('PaymentCompletedListener', () => {
  let listener: PaymentCompletedListener;
  let mockCommandBus: { execute: ReturnType<typeof vi.fn> };
  let mockPrisma: { user: { findUnique: ReturnType<typeof vi.fn> } };
  let mockLogger: { log: ReturnType<typeof vi.fn>; warn: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn> };

  beforeEach(() => {
    mockCommandBus = { execute: vi.fn().mockResolvedValue(undefined) };
    mockPrisma = {
      user: { findUnique: vi.fn() },
    };
    mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn() };

    listener = new PaymentCompletedListener(
      mockCommandBus as any,
      mockPrisma as any,
      mockLogger as any,
    );
  });

  it('sends payment confirmation email', async () => {
    mockPrisma.user.findUnique.mockResolvedValue({ email: 'buyer@test.com' });

    const event = new PaymentCompletedEvent('pay-1', 'user-1', 'VNPAY', BigInt(5000000));
    await listener.handle(event);

    const cmd = mockCommandBus.execute.mock.calls[0]![0] as SendNotificationCommand;
    expect(cmd.userId).toBe('user-1');
    expect(cmd.channel).toBe('EMAIL');
    expect(cmd.templateKey).toBe('payment.confirmed');
    expect(cmd.templateData.paymentId).toBe('pay-1');
    expect(cmd.templateData.provider).toBe('VNPAY');
    expect(cmd.recipientAddress).toBe('buyer@test.com');
  });

  it('skips notification when user not found', async () => {
    mockPrisma.user.findUnique.mockResolvedValue(null);

    const event = new PaymentCompletedEvent('pay-1', 'user-1', 'VNPAY', BigInt(5000000));
    await listener.handle(event);

    expect(mockCommandBus.execute).not.toHaveBeenCalled();
  });

  it('skips notification when user has no email', async () => {
    mockPrisma.user.findUnique.mockResolvedValue({ email: null });

    const event = new PaymentCompletedEvent('pay-1', 'user-1', 'VNPAY', BigInt(5000000));
    await listener.handle(event);

    expect(mockCommandBus.execute).not.toHaveBeenCalled();
  });
});
