package com.mvrent.carrental.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * Low-level SMTP sender. Separate bean so {@code @Async} actually applies when
 * called from {@link NotificationService} (self-invocation would bypass the proxy).
 * Sends only plain strings, so it is safe to run off the request thread.
 */
@Component
@Slf4j
public class MailDispatcher {

    private final ObjectProvider<JavaMailSender> mailSenderProvider;

    @Value("${app.mail.enabled:false}")
    private boolean mailEnabled;
    @Value("${app.mail.from:no-reply@mvrent.local}")
    private String from;

    public MailDispatcher(ObjectProvider<JavaMailSender> mailSenderProvider) {
        this.mailSenderProvider = mailSenderProvider;
    }

    public boolean isReady() {
        return mailEnabled && mailSenderProvider.getIfAvailable() != null;
    }

    /** Fire-and-forget send; never throws. */
    @Async
    public void send(String to, String subject, String body) {
        JavaMailSender sender = mailSenderProvider.getIfAvailable();
        if (!mailEnabled || sender == null) {
            log.info("[email skipped — not configured] to={} subject={}", to, subject);
            return;
        }
        try {
            sender.send(message(to, subject, body));
            log.info("Sent email to {}: {}", to, subject);
        } catch (Exception ex) {
            log.warn("Email send failed to {}: {}", to, ex.getMessage());
        }
    }

    /** Synchronous send used by the test button; throws so the UI sees the error. */
    public void sendNow(String to, String subject, String body) {
        if (!isReady()) {
            throw new IllegalStateException("Email is not configured (set spring.mail.host and app.mail.enabled=true)");
        }
        mailSenderProvider.getObject().send(message(to, subject, body));
        log.info("Sent email to {}: {}", to, subject);
    }

    private SimpleMailMessage message(String to, String subject, String body) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(from);
        msg.setTo(to);
        msg.setSubject(subject);
        msg.setText(body);
        return msg;
    }
}
