package dev.rheinsw.mail.controller;

import dev.rheinsw.mail.service.MailService;
import dev.rheinsw.shared.mail.dto.MailRequest;
import jakarta.mail.MessagingException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import org.springframework.http.ResponseEntity;

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

class MailControllerTest {

    @Mock
    private MailService mailService;

    @InjectMocks
    private MailController mailController;

    private AutoCloseable closeable;

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

    @Test
    void sendEmail_shouldReturnOk_whenEmailSentSuccessfully() throws MessagingException {
        // Arrange
        MailRequest request = new MailRequest("user@example.com", "Test Subject", "Message");

        // Act
        ResponseEntity<String> response = mailController.sendEmail(request);

        // Assert
        verify(mailService).sendEmail(request);
        assertEquals(200, response.getStatusCodeValue());
        assertEquals("Email sent successfully", response.getBody());
    }

    @Test
    void sendEmail_shouldReturnServerError_whenMessagingExceptionThrown() throws MessagingException {
        // Arrange
        MailRequest request = new MailRequest("user@example.com", "Test Subject", "Message");
        doThrow(new MessagingException("SMTP failed")).when(mailService).sendEmail(request);

        // Act
        ResponseEntity<String> response = mailController.sendEmail(request);

        // Assert
        verify(mailService).sendEmail(request);
        assertEquals(500, response.getStatusCodeValue());
        assertTrue(response.getBody().contains("Failed to send email: SMTP failed"));
    }

    @AfterEach
    void tearDown() throws Exception {
        closeable.close();
    }
}
