package de.cannamanage.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * Email service for sending invite emails to new staff members.
 * Uses plain text templates — no Thymeleaf dependency needed.
 */
@Slf4j
@Service
public class EmailService {

    private final JavaMailSender mailSender;
    private final String baseUrl;
    private final String fromAddress;

    public EmailService(JavaMailSender mailSender,
                        @Value("${app.base-url:http://localhost:8080}") String baseUrl,
                        @Value("${spring.mail.from:noreply@cannamanage.de}") String fromAddress) {
        this.mailSender = mailSender;
        this.baseUrl = baseUrl;
        this.fromAddress = fromAddress;
    }

    /**
     * Sends an invite email to a new staff member with a link to set their password.
     * Security: token value is NOT logged.
     */
    public void sendInviteEmail(String recipientEmail, String displayName,
                                String clubName, String token) {
        String setPasswordUrl = baseUrl + "/auth/set-password?token=" + token;

        String body = String.format("""
                Hallo %s,

                Du wurdest als Mitarbeiter/in beim Anbauverein "%s" eingeladen.

                Bitte klicke auf den folgenden Link, um dein Passwort festzulegen und deinen Account zu aktivieren:

                %s

                Dieser Link ist 72 Stunden gültig.

                Falls du diese Einladung nicht erwartet hast, kannst du diese E-Mail ignorieren.

                Viele Grüße,
                Dein CannaManage-Team
                """, displayName, clubName, setPasswordUrl);

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromAddress);
        message.setTo(recipientEmail);
        message.setSubject("Einladung: " + clubName + " — Account aktivieren");
        message.setText(body);

        try {
            mailSender.send(message);
            log.info("Invite email sent to {} for club '{}'", recipientEmail, clubName);
        } catch (Exception e) {
            log.error("Failed to send invite email to {}: {}", recipientEmail, e.getMessage());
            throw new RuntimeException("Failed to send invite email", e);
        }
    }
}
