package com.prudas.app.service;

import com.prudas.app.config.AppProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * Thin notification wrapper. When app.mail.notifications-enabled=false
 * (the default, so the project runs without SMTP credentials configured),
 * this just logs — it never throws, so a mail outage can never break the
 * contact form or newsletter signup flow for the visitor.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MailService {

    private final JavaMailSender mailSender;
    private final AppProperties appProperties;

    public void notifyNewContactSubmission(String fromName, String fromEmail, String subject, String message) {
        if (!appProperties.mail().notificationsEnabled()) {
            log.info("Mail notifications disabled; new contact submission from {} <{}> logged only", fromName, fromEmail);
            return;
        }
        try {
            SimpleMailMessage mail = new SimpleMailMessage();
            mail.setFrom(appProperties.mail().fromAddress());
            mail.setTo(appProperties.mail().contactNotifyAddress());
            mail.setReplyTo(fromEmail);
            mail.setSubject("New contact form submission: " + (subject == null || subject.isBlank() ? "(no subject)" : subject));
            mail.setText("From: " + fromName + " <" + fromEmail + ">\n\n" + message);
            mailSender.send(mail);
        } catch (Exception ex) {
            // A downstream mail failure must never surface as a 500 to the
            // visitor who just submitted the form — the lead is already
            // safely persisted in contact_submissions.
            log.error("Failed to send contact notification email", ex);
        }
    }

    public void sendNewsletterConfirmation(String toEmail, String confirmationLink) {
        if (!appProperties.mail().notificationsEnabled()) {
            log.info("Mail notifications disabled; newsletter confirmation link for {}: {}", toEmail, confirmationLink);
            return;
        }
        try {
            SimpleMailMessage mail = new SimpleMailMessage();
            mail.setFrom(appProperties.mail().fromAddress());
            mail.setTo(toEmail);
            mail.setSubject("Confirm your subscription to the Prudas newsletter");
            mail.setText("Thanks for subscribing! Please confirm your email address:\n\n" + confirmationLink
                    + "\n\nIf you didn't request this, you can ignore this email.");
            mailSender.send(mail);
        } catch (Exception ex) {
            log.error("Failed to send newsletter confirmation email", ex);
        }
    }
}
