package io.ljunggren.sendgrid.api.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
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.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;

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

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

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

class SuppressionServiceTest {

	private SendGrid sendGrid;
	private SuppressionService service;

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

	private void respond(int status) throws IOException {
		Response response = new Response();
		response.setStatusCode(status);
		response.setBody("{}");
		when(sendGrid.api(any(Request.class))).thenReturn(response);
	}

	@ParameterizedTest
	@ValueSource(ints = { 204, 200, 404 })
	void deleteGroupSuppression_deletesFromTheGroup(int status) throws Exception {
		respond(status);

		service.deleteGroupSuppression(4321, "dave@example.com");

		ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
		verify(sendGrid).api(captor.capture());
		assertEquals(Method.DELETE, captor.getValue().getMethod());
		assertEquals("asm/groups/4321/suppressions/dave@example.com", captor.getValue().getEndpoint());
	}

	@Test
	void deleteGroupSuppression_otherStatus_throws() throws Exception {
		respond(401);
		SendgridException ex = assertThrows(SendgridException.class,
				() -> service.deleteGroupSuppression(1, "dave@example.com"));
		assertEquals(true, ex.getMessage().contains("401"));
	}

	@Test
	void deleteGroupSuppression_ioException_isWrapped() throws Exception {
		IOException ioe = new IOException("network down");
		when(sendGrid.api(any(Request.class))).thenThrow(ioe);
		SendgridException ex = assertThrows(SendgridException.class,
				() -> service.deleteGroupSuppression(1, "dave@example.com"));
		assertSame(ioe, ex.getCause());
	}

	@Test
	void deleteGroupSuppression_rejectsBlankEmail() {
		assertThrows(IllegalArgumentException.class, () -> service.deleteGroupSuppression(1, " "));
	}

}
