package com.example.dateplanner.services;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailService {

    @Value("${app.system.email}")
    private String fromEmail;

    private final JavaMailSender mailSender;

    public Mono<Void> send(String toEmail, String subject, String htmlBody) {
        return Mono.fromCallable(() -> {
                    MimeMessage message = mailSender.createMimeMessage();
                    MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
                    helper.setFrom(fromEmail);
                    helper.setTo(toEmail);
                    helper.setSubject(subject);
                    helper.setText(htmlBody, true);
                    mailSender.send(message);
                    return true;
                })
                .subscribeOn(Schedulers.boundedElastic())
                .doOnError(e -> log.error("Не удалось отправить письмо на {}: {}", toEmail, e.getMessage()))
                .then();
    }
}
