package cz.muni.fi.pa165.microservice3.email;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/api/email")
@Tag(name = "Email", description = "Email API")
public class EmailController {

	private final EmailService emailService;

	@Autowired
	public EmailController(EmailService emailService) {
		this.emailService = emailService;
	}

	@Operation(
			summary = "Send email to given email address with given subject and body",
			description = "If email address is valid mail will be send to given address with given subject and body.")
	@PostMapping(value = "/send", consumes = "application/json", produces = "application/json")
	@ApiResponses(
			value = {
					@ApiResponse(responseCode = "200", description = "Email sent successfully"),
					@ApiResponse(responseCode = "400", description = "Invalid input"),
					@ApiResponse(responseCode = "401", description = "Authentication failed")
			}
	)
	public EmailTemplate sendEmail(@RequestBody EmailTemplate emailTemplate) {

		var emailAddress = emailTemplate.getSendTo();
		if (!EmailUtils.isValidEmail(emailAddress))
			throw new ResponseStatusException(
					HttpStatus.BAD_REQUEST, "Failed to send email. Error: " + emailAddress + " is not valid email address.");

		try {
			emailService.send(emailTemplate);
			return emailTemplate;
		} catch (MailAuthenticationException e) {
			throw new ResponseStatusException(
					HttpStatus.UNAUTHORIZED, "Authentication failed. Error: " + e);
		} catch (MailSendException e) {
			throw new ResponseStatusException(
					HttpStatus.BAD_REQUEST, "Mail sending error:" + e);
		} catch (MailException e) {
			throw new ResponseStatusException(
					HttpStatus.BAD_REQUEST, "Failed to send email. Error: " + e);
		}


	}

}
