package com.alttd.altitudeweb.services.mail;

import com.alttd.altitudeweb.database.web_db.forms.StaffApplication;
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 org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
@RequiredArgsConstructor
public class StaffApplicationMail {

    private final JavaMailSender mailSender;
    private final SpringTemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String fromEmail;

    private static final String STAFF_APPLICATION_EMAIL = "apply@alttd.com";

    /**
     * Sends an email with the staff application details to the staff applications team mailbox.
     * Returns true if the email was sent successfully.
     */
    public boolean sendApplicationEmail(String username, StaffApplication application) {
        try {
            doSend(username, application);
            log.info("Staff application email sent successfully for application ID: {}", application.id());
            return true;
        } catch (Exception e) {
            log.error("Failed to send staff application email for application ID: {}", application.id(), e);
            return false;
        }
    }

    private void doSend(String username, StaffApplication application) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(fromEmail);
        helper.setTo(STAFF_APPLICATION_EMAIL);
        helper.setReplyTo(application.email());
        helper.setSubject("Staff Application: " + safe(application.discordUsername()));

        // Prepare template context
        String createdAt = application.createdAt()
                .atZone(ZoneId.of("UTC"))
                .format(DateTimeFormatter.ofPattern("yyyy MMMM dd hh:mm a '(UTC)'"));
        Context context = new Context();
        context.setVariable("application", application);
        context.setVariable("createdAt", createdAt);
        context.setVariable("username", username);

        String content = templateEngine.process("staff-application-email", context);
        helper.setText(content, true);
        mailSender.send(message);
    }

    private String safe(String s) {
        return s == null ? "unknown" : s;
    }
}
