package de.cannamanage.service;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class EmailServiceTest {

    @Mock
    private JavaMailSender mailSender;

    private EmailService emailService;

    @Test
    void sendInviteEmail_sendsCorrectContent() {
        emailService = new EmailService(mailSender, "https://app.cannamanage.de", "noreply@cannamanage.de");

        emailService.sendInviteEmail("staff@example.com", "Max Mustermann", "Green Club", "abc123token");

        ArgumentCaptor<SimpleMailMessage> captor = ArgumentCaptor.forClass(SimpleMailMessage.class);
        verify(mailSender).send(captor.capture());

        SimpleMailMessage msg = captor.getValue();
        assertThat(msg.getTo()).contains("staff@example.com");
        assertThat(msg.getFrom()).isEqualTo("noreply@cannamanage.de");
        assertThat(msg.getSubject()).contains("Green Club");
        assertThat(msg.getText()).contains("Max Mustermann");
        assertThat(msg.getText()).contains("https://app.cannamanage.de/auth/set-password?token=abc123token");
        assertThat(msg.getText()).contains("72 Stunden");
    }

    @Test
    void sendInviteEmail_mailFailure_throwsRuntimeException() {
        emailService = new EmailService(mailSender, "http://localhost:8080", "noreply@cannamanage.de");
        doThrow(new RuntimeException("SMTP error")).when(mailSender).send(any(SimpleMailMessage.class));

        assertThatThrownBy(() ->
                emailService.sendInviteEmail("fail@example.com", "Fail User", "Club", "token123"))
                .isInstanceOf(RuntimeException.class)
                .hasMessageContaining("Failed to send invite email");
    }
}
