package io.ljunggren.sendgrid.api.service;

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

import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.ASM;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;

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

/**
 * Service that sends emails via the SendGrid v3 mail/send endpoint.
 */
public class EmailService extends BaseService {

	private static final String MAIL_SEND_ENDPOINT = "mail/send";
	private static final String DEFAULT_CONTENT_TYPE = "text/plain";

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

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

	/**
	 * Send a simple plain-text email.
	 *
	 * @param from    sender address (must not be null or blank)
	 * @param to      recipient address (must not be null or blank)
	 * @param subject email subject
	 * @param body    plain-text body
	 * @throws SendgridException if the email cannot be sent
	 */
	public void sendEmail(String from, String to, String subject, String body) throws SendgridException {
		requireNonBlank(from, "from");
		requireNonBlank(to, "to");
		Mail mail = new Mail(
				new Email(from),
				subject,
				new Email(to),
				new Content(DEFAULT_CONTENT_TYPE, body));
		sendEmail(mail);
	}

	/**
	 * Send a templated email using SendGrid dynamic templates.
	 *
	 * @param templateId   SendGrid template id (must not be null or blank)
	 * @param from         sender address (must not be null or blank)
	 * @param to           recipient address (must not be null or blank)
	 * @param templateData substitution variables; may be null or empty
	 * @throws SendgridException if the email cannot be sent
	 */
	public void sendTemplateEmail(String templateId, String from, String to, Map<String, Object> templateData) throws SendgridException {
		sendTemplateEmail(templateId, from, to, templateData, null);
	}

	/**
	 * Send a templated email in an unsubscribe group (SendGrid's "Advanced Suppression Manager"). SendGrid then adds
	 * its List-Unsubscribe header, fills the template's {@code {{{unsubscribe}}}} and
	 * {@code {{{unsubscribe_preferences}}}} links, and skips recipients who unsubscribed from that group.
	 *
	 * @param templateId   SendGrid template id (must not be null or blank)
	 * @param from         sender address (must not be null or blank)
	 * @param to           recipient address (must not be null or blank)
	 * @param templateData substitution variables; may be null or empty
	 * @param asmGroupId   unsubscribe group id; null for none (e.g. transactional email)
	 * @throws SendgridException if the email cannot be sent
	 */
	public void sendTemplateEmail(String templateId, String from, String to, Map<String, Object> templateData,
			Integer asmGroupId) throws SendgridException {
		requireNonBlank(templateId, "templateId");
		requireNonBlank(from, "from");
		requireNonBlank(to, "to");
		Mail mail = new Mail();
		mail.setTemplateId(templateId);
		mail.setFrom(new Email(from));
		Personalization personalization = new Personalization();
		personalization.addTo(new Email(to));
		if (templateData != null) {
			templateData.forEach(personalization::addDynamicTemplateData);
		}
		mail.addPersonalization(personalization);
		if (asmGroupId != null) {
			ASM asm = new ASM();
			asm.setGroupId(asmGroupId);
			asm.setGroupsToDisplay(new int[] { asmGroupId });
			mail.setASM(asm);
		}
		sendEmail(mail);
	}

	private void sendEmail(Mail mail) throws SendgridException {
		try {
			Request request = new Request();
			request.setMethod(Method.POST);
			request.setEndpoint(MAIL_SEND_ENDPOINT);
			request.setBody(mail.build());
			Response response = sendGrid.api(request);
			if (response.getStatusCode() == HttpURLConnection.HTTP_ACCEPTED) {
				return;
			}
			throw new SendgridException(
					"Error sending email. status=" + response.getStatusCode()
							+ ", body=" + response.getBody());
		} catch (IOException e) {
			throw new SendgridException("Failed to send email", e);
		}
	}

	private static void requireNonBlank(String value, String name) {
		if (value == null || value.isBlank()) {
			throw new IllegalArgumentException(name + " must not be null or blank");
		}
	}

}
