package io.ljunggren.sendgrid.api.service;

import java.io.IOException;
import java.net.HttpURLConnection;

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

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

/**
 * Service for SendGrid's unsubscribe groups (the v3 asm/groups suppressions endpoints).
 */
public class SuppressionService extends BaseService {

	/**
	 * Create a new {@code SuppressionService} backed by a real SendGrid client.
	 *
	 * @param apiKey the SendGrid API key
	 * @throws IllegalArgumentException if {@code apiKey} is null or blank
	 */
	public SuppressionService(String apiKey) {
		super(apiKey);
	}

	/**
	 * Test-only constructor that accepts a pre-built (possibly mocked) client.
	 *
	 * @param sendGrid the SendGrid client to use
	 */
	SuppressionService(SendGrid sendGrid) {
		super(sendGrid);
	}

	/**
	 * Take an address off an unsubscribe group's suppression list, so it receives that group's emails again (for
	 * when the person opts back in somewhere else). An address that wasn't suppressed is fine too.
	 *
	 * @param groupId unsubscribe group id
	 * @param email   the address (must not be null or blank)
	 * @throws SendgridException if SendGrid refuses or can't be reached
	 */
	public void deleteGroupSuppression(int groupId, String email) throws SendgridException {
		if (email == null || email.isBlank()) {
			throw new IllegalArgumentException("email must not be null or blank");
		}
		try {
			Request request = new Request();
			request.setMethod(Method.DELETE);
			// Not URL-encoded here: the client builds the URL from the path and encodes it itself
			request.setEndpoint("asm/groups/" + groupId + "/suppressions/" + email.strip());
			Response response = sendGrid.api(request);
			int status = response.getStatusCode();
			if (status == HttpURLConnection.HTTP_NO_CONTENT || status == HttpURLConnection.HTTP_OK
					|| status == HttpURLConnection.HTTP_NOT_FOUND) {
				return;
			}
			throw new SendgridException("Error removing suppression. status=" + status + ", body=" + response.getBody());
		} catch (IOException e) {
			throw new SendgridException("Failed to remove suppression", e);
		}
	}

}
