package dev.rheinsw.server.mail.usecase;


import dev.rheinsw.server.mail.domain.MailRequest;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.mail.javamail.JavaMailSender;

/**
 * @author Thatsaphorn Atchariyaphap
 * @since 04.05.25
 */
@Service
public class SendMailUseCase implements ISendMailUseCase {
    private final JavaMailSender mailSender;

    public SendMailUseCase(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Override
    public ResponseEntity<String> execute(MailRequest request) {
        try {
            sendEmail(request);
            return ResponseEntity.ok("Email sent successfully");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to send email: " + e.getMessage());
        }
    }

    private void sendEmail(MailRequest request) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom("noreply@rhein-software.dev");
        helper.setTo(request.getTo());
        helper.setSubject(request.getSubject());
        helper.setText(request.getMessage(), false);

        mailSender.send(message);
    }

}
