package io.ljunggren.sendgrid.api.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;

import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;

import io.ljunggren.sendgrid.api.exception.SendgridException;

class EmailServiceTest {

	private SendGrid sendGrid;
	private EmailService service;

	@BeforeEach
	void setUp() {
		sendGrid = org.mockito.Mockito.mock(SendGrid.class);
		service = new EmailService(sendGrid);
	}

	@Test
	void publicConstructor_rejectsBlankApiKey() {
		assertThrows(IllegalArgumentException.class, () -> new EmailService(""));
	}

	@Test
	void sendEmail_success_returnsNormally() throws Exception {
		Response response = new Response();
		response.setStatusCode(202);
		when(sendGrid.api(any(Request.class))).thenReturn(response);

		service.sendEmail("from@x.com", "to@y.com", "subject", "body");

		ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
		verify(sendGrid, times(1)).api(captor.capture());
		Request sent = captor.getValue();
		assertEquals("mail/send", sent.getEndpoint());
		assertNotNull(sent.getBody());
	}

	@Test
	void sendEmail_non202Response_throws() throws Exception {
		Response response = new Response();
		response.setStatusCode(400);
		response.setBody("invalid request");
		when(sendGrid.api(any(Request.class))).thenReturn(response);

		SendgridException ex = assertThrows(SendgridException.class,
				() -> service.sendEmail("from@x.com", "to@y.com", "subj", "body"));
		assertNotNull(ex.getMessage());
		// Message should include the status code we got back.
		assertEquals(true, ex.getMessage().contains("400"));
	}

	@Test
	void sendEmail_ioExceptionFromClient_isWrappedWithCause() throws Exception {
		IOException ioe = new IOException("network down");
		when(sendGrid.api(any(Request.class))).thenThrow(ioe);

		SendgridException ex = assertThrows(SendgridException.class,
				() -> service.sendEmail("from@x.com", "to@y.com", "subj", "body"));
		assertSame(ioe, ex.getCause());
	}

	@ParameterizedTest
	@NullAndEmptySource
	@ValueSource(strings = { "  " })
	void sendEmail_rejectsNullOrBlankFrom(String from) {
		assertThrows(IllegalArgumentException.class,
				() -> service.sendEmail(from, "to@y.com", "s", "b"));
	}

	@ParameterizedTest
	@NullAndEmptySource
	@ValueSource(strings = { "  " })
	void sendEmail_rejectsNullOrBlankTo(String to) {
		assertThrows(IllegalArgumentException.class,
				() -> service.sendEmail("from@x.com", to, "s", "b"));
	}

	@Test
	void sendTemplateEmail_success() throws Exception {
		Response response = new Response();
		response.setStatusCode(202);
		when(sendGrid.api(any(Request.class))).thenReturn(response);

		Map<String, Object> data = new HashMap<>();
		data.put("name", "World");
		service.sendTemplateEmail("tpl-1", "from@x.com", "to@y.com", data);

		verify(sendGrid, times(1)).api(any(Request.class));
	}

	@Test
	void sendTemplateEmail_nullTemplateData_doesNotThrowNpe() throws Exception {
		Response response = new Response();
		response.setStatusCode(202);
		when(sendGrid.api(any(Request.class))).thenReturn(response);

		service.sendTemplateEmail("tpl-1", "from@x.com", "to@y.com", null);

		verify(sendGrid, times(1)).api(any(Request.class));
	}

	@ParameterizedTest
	@NullAndEmptySource
	@ValueSource(strings = { "  " })
	void sendTemplateEmail_rejectsNullOrBlankTemplateId(String id) {
		assertThrows(IllegalArgumentException.class,
				() -> service.sendTemplateEmail(id, "from@x.com", "to@y.com", null));
	}

	@Test
	void sendTemplateEmail_non202_throwsAndPreservesContext() throws Exception {
		Response response = new Response();
		response.setStatusCode(500);
		response.setBody("server error");
		when(sendGrid.api(any(Request.class))).thenReturn(response);

		SendgridException ex = assertThrows(SendgridException.class,
				() -> service.sendTemplateEmail("tpl", "f@x.com", "t@y.com", null));
		assertNull(ex.getCause());
		assertEquals(true, ex.getMessage().contains("500"));
	}

}
