package de.szut.casino.security.service;

import de.szut.casino.deposit.TransactionEntity;
import de.szut.casino.user.UserEntity;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

@Service
public class EmailService {
    private JavaMailSenderImpl mailSender;
    private MailConfig mailConfig;
    @Value("${app.frontend-host}")
    private String feUrl;

    public EmailService(JavaMailSenderImpl mailSender, MailConfig mailConfig) {
        this.mailSender = mailSender;
        this.mailConfig = mailConfig;
        this.mailSender.setHost(mailConfig.host);
        this.mailSender.setPort(mailConfig.port);
        this.mailSender.setProtocol(mailConfig.protocol);
        if (mailConfig.authenticationEnabled) {
            this.mailSender.setUsername(mailConfig.username);
            this.mailSender.setPassword(mailConfig.password);
        }
    }

    public void sendEmailVerificationEmail(UserEntity user) throws IOException, MessagingException {
        String template = loadTemplate("email/verify.html");
        String htmlContent = template
                .replace("${username}", user.getUsername())
                .replace("${feUrl}", feUrl)
                .replace("${token}", user.getVerificationToken());

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(mailConfig.fromAddress);
        helper.setTo(user.getEmailAddress());
        helper.setSubject("E-Mail Bestätigung");
        helper.setText(htmlContent, true);

        mailSender.send(message);
    }

    public void sendWelcomeEmail(UserEntity user) throws IOException, MessagingException {
        String template = loadTemplate("email/welcome.html");
        String htmlContent = template
                .replace("${username}", user.getUsername())
                .replace("${feUrl}", feUrl);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(mailConfig.fromAddress);
        helper.setTo(user.getEmailAddress());
        helper.setSubject("Willkommen bei Trustworthy Casino©");
        helper.setText(htmlContent, true);

        mailSender.send(message);
    }

    public void sendDepositEmail(TransactionEntity transaction) throws IOException, MessagingException {
        String template = loadTemplate("email/deposit.html");
        String htmlContent = template
                .replace("${username}", transaction.getUser().getUsername())
                .replace("${amount}", String.valueOf(transaction.getAmount()))
                .replace("${feUrl}", feUrl);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(mailConfig.fromAddress);
        helper.setTo(transaction.getUser().getEmailAddress());
        helper.setSubject("Einzahlung über ${amount}€ Erfolgreich".replace("${amount}", String.valueOf(transaction.getAmount())));
        helper.setText(htmlContent, true);

        mailSender.send(message);
    }

    public void sendPasswordRecoveryEmail(UserEntity user) throws IOException, MessagingException {
        String template = loadTemplate("email/recover-password.html");
        String htmlContent = template
                .replace("${username}", user.getUsername())
                .replace("${resetToken}", user.getPasswordResetToken())
                .replace("${feUrl}", feUrl);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(mailConfig.fromAddress);
        helper.setTo(user.getEmailAddress());
        helper.setSubject("Zurücksetzen ihres Passworts");
        helper.setText(htmlContent, true);

        mailSender.send(message);
    }

    private String loadTemplate(String templatePath) throws IOException {
        ClassPathResource resource = new ClassPathResource("templates/" + templatePath);
        try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
            return FileCopyUtils.copyToString(reader);
        }
    }
}
