// Mock dependencies
jest.mock('../../../../../services/email/core/EmailClient', () => {
  return jest.fn().mockImplementation(() => ({
    initialize: jest.fn().mockResolvedValue(),
    sendEmail: jest.fn().mockResolvedValue({ success: true, messageId: 'msg-123' }),
  }));
});

jest.mock('../../../../../services/email/core/TemplateManager', () => {
  return jest.fn().mockImplementation(() => ({
    initialize: jest.fn().mockResolvedValue(),
    renderTemplate: jest.fn().mockResolvedValue('<html>Test</html>'),
  }));
});

jest.mock('../../../../../utils/logger', () => ({
  info: jest.fn(),
  error: jest.fn(),
  warn: jest.fn(),
}));

const MessagingEmailService = require('../../../../../services/email/domain/MessagingEmailService');

describe('MessagingEmailService', () => {
  let service;
  const originalEnv = process.env;

  beforeEach(() => {
    jest.clearAllMocks();
    process.env = { ...originalEnv, FRONTEND_URL: 'http://localhost:3000' };
    service = new MessagingEmailService();
  });

  afterEach(() => {
    process.env = originalEnv;
  });

  describe('initialize', () => {
    it('should initialize only once', async () => {
      await service.initialize();
      await service.initialize();

      expect(service.emailClient.initialize).toHaveBeenCalledTimes(1);
      expect(service.templateManager.initialize).toHaveBeenCalledTimes(1);
    });
  });

  describe('sendNewMessageNotification', () => {
    const receiver = { firstName: 'John', email: 'john@example.com' };
    const sender = { id: 456, firstName: 'Jane', lastName: 'Smith' };
    const message = {
      content: 'Hello, is the power drill still available?',
      createdAt: '2024-01-15T10:00:00Z',
    };

    it('should send new message notification with correct variables', async () => {
      const result = await service.sendNewMessageNotification(receiver, sender, message);

      expect(result.success).toBe(true);
      expect(service.templateManager.renderTemplate).toHaveBeenCalledWith(
        'newMessageToUser',
        expect.objectContaining({
          recipientName: 'John',
          senderName: 'Jane Smith',
          messageContent: 'Hello, is the power drill still available?',
          conversationUrl: 'http://localhost:3000/messages/conversations/456',
        })
      );
      expect(service.emailClient.sendEmail).toHaveBeenCalledWith(
        'john@example.com',
        'New message from Jane Smith',
        expect.any(String)
      );
    });

    it('should use default name when receiver firstName is missing', async () => {
      const receiverNoName = { email: 'john@example.com' };

      await service.sendNewMessageNotification(receiverNoName, sender, message);

      expect(service.templateManager.renderTemplate).toHaveBeenCalledWith(
        'newMessageToUser',
        expect.objectContaining({ recipientName: 'there' })
      );
    });

    it('should use A user fallback when sender names produce empty string', async () => {
      const senderEmptyNames = { id: 456, firstName: '', lastName: '' };

      await service.sendNewMessageNotification(receiver, senderEmptyNames, message);

      expect(service.templateManager.renderTemplate).toHaveBeenCalledWith(
        'newMessageToUser',
        expect.objectContaining({ senderName: 'A user' })
      );
    });

    it('should handle errors gracefully', async () => {
      service.templateManager.renderTemplate.mockRejectedValueOnce(new Error('Template error'));

      const result = await service.sendNewMessageNotification(receiver, sender, message);

      expect(result.success).toBe(false);
      expect(result.error).toBe('Template error');
    });
  });
});
