package dev.rheinsw.mail.service;

import dev.rheinsw.shared.mail.dto.MailRequest;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;

class MailServiceTest {

    @Mock
    private JavaMailSender mailSender;

    @InjectMocks
    private MailService mailService;

    private AutoCloseable closeable;

    @BeforeEach
    void setUp() {
        closeable = MockitoAnnotations.openMocks(this);
    }

    @Test
    void sendEmail_shouldSendMessageSuccessfully() throws MessagingException {
        // Arrange
        MailRequest request = new MailRequest("user@example.com", "Hello", "This is a test message.");
        MimeMessage mimeMessage = mock(MimeMessage.class);
        when(mailSender.createMimeMessage()).thenReturn(mimeMessage);

        // Act & Assert
        assertDoesNotThrow(() -> mailService.sendEmail(request));
        verify(mailSender).send(mimeMessage);
    }

    @Test
    void sendEmail_shouldThrowMessagingException_whenMailSenderFails() {
        // Arrange
        MailRequest request = new MailRequest("user@example.com", "Hello", "This is a test message.");
        MimeMessage mimeMessage = mock(MimeMessage.class);
        when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
        doThrow(new RuntimeException("Simulated failure")).when(mailSender).send(mimeMessage);

        // Act & Assert
        RuntimeException exception = assertThrows(RuntimeException.class, () -> {
            mailService.sendEmail(request);
        });

        assertEquals("Simulated failure", exception.getMessage());
    }

}
