package com.example.demo.service;

import java.util.Hashtable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import com.example.demo.repository.UserRepo;

import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;
    
    @Autowired
    private OtpStore otpStore;
    
    @Autowired
    private UserRepo userRepository;
    
    public void sendOtpEmail(String toEmail) {
        String otp = OtpUtil.generateOtp(6);
        otpStore.save(toEmail, otp);

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(toEmail);
        message.setSubject("Welcome to Thyme Crunch – Verify Your Account");
        message.setText(
            "Welcome to Thyme Crunch!\n\n" +
            "Your verification code: " + otp + "\n\n" +
            "This code will expire in 5 minutes.\n\n" +
            "If you did not create an account, ignore this email.\n\n" +
            "The Thyme Crunch Team"
        );

        try {
            mailSender.send(message);
        } catch (MailException e) {
            otpStore.clear(toEmail);
            throw new RuntimeException("Failed to send email to: " + toEmail, e);
        }
    }
    
    public boolean isEmailTaken(String email) {
        return userRepository.findByEmail(email.toLowerCase().trim()).isPresent();
    }
    
    public boolean isValidEmail(String email) {
        if (email == null || email.isBlank()) return false;

        String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
        if (!email.matches(emailRegex)) return false;
        

        try {
            InternetAddress emailAddr = new InternetAddress(email, true);
            emailAddr.validate();
        } catch (AddressException ex) {
            return false;
        }

        String domain = email.substring(email.indexOf('@') + 1);
        return hasMxRecord(domain);
    }
    

private boolean hasMxRecord(String domain) {
    try {
        Hashtable<String, String> env = new Hashtable<>();
        env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        env.put("java.naming.provider.url", "dns:");
        env.put("com.sun.jndi.dns.timeout.initial", "2000");
        env.put("com.sun.jndi.dns.timeout.retries", "1");

        DirContext ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(domain, new String[]{"MX"});
        return attrs.get("MX") != null;
    } catch (Exception e) {
        return false;
    }
}
}