import { SubscriptionCancelledEvent } from '@modules/subscriptions/domain/events/subscription-cancelled.event';
import type { SendNotificationCommand } from '../commands/send-notification/send-notification.command';
import { SubscriptionExpiringListener } from '../listeners/subscription-expiring.listener';

describe('SubscriptionExpiringListener', () => {
  let listener: SubscriptionExpiringListener;
  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 SubscriptionExpiringListener(
      mockCommandBus as any,
      mockPrisma as any,
      mockLogger as any,
    );
  });

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

    const event = new SubscriptionCancelledEvent('sub-1', 'user-1', 'PRO');
    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('subscription.expiring');
    expect(cmd.templateData).toEqual({ planTier: 'PRO' });
    expect(cmd.recipientAddress).toBe('user@test.com');
  });

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

    const event = new SubscriptionCancelledEvent('sub-1', 'user-1', 'PRO');
    await listener.handle(event);

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