package auctiora;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;

import javax.mail.*;
import javax.mail.internet.*;
import lombok.extern.slf4j.Slf4j;
import java.awt.*;
import java.util.Date;
import java.util.Properties;

@Slf4j
public class NotificationService {

   private final Config config;

   public NotificationService(String cfg) {
      this.config = Config.parse(cfg);
   }
   
   public void sendNotification(String message, String title, int priority) {
      if (config.useDesktop()) sendDesktop(title, message, priority);
      if (config.useEmail()) sendEmail(title, message, priority);
   }
   
   private void sendDesktop(String title, String msg, int prio) {
      try {
         if (!SystemTray.isSupported()) {
            log.info("Desktop notifications not supported — " + title + " / " + msg);
            return;
         }
         var tray     = SystemTray.getSystemTray();
         var image    = Toolkit.getDefaultToolkit().createImage(new byte[0]);
         var trayIcon = new TrayIcon(image, "NotificationService");
         trayIcon.setImageAutoSize(true);
         var type = prio > 0 ? TrayIcon.MessageType.WARNING : TrayIcon.MessageType.INFO;
         tray.add(trayIcon);
         trayIcon.displayMessage(title, msg, type);
         Thread.sleep(2000);
         tray.remove(trayIcon);
         log.info("Desktop notification sent: " + title);
      } catch (Exception e) {
         System.err.println("Desktop notification failed: " + e);
      }
   }
   
   private void sendEmail(String title, String msg, int prio) {
      try {
         var props = new Properties();
         props.put("mail.smtp.auth", "true");
         props.put("mail.smtp.starttls.enable", "true");
         props.put("mail.smtp.host", "smtp.gmail.com");
         props.put("mail.smtp.port", "587");
         props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
         
         var session = Session.getInstance(props, new Authenticator() {
            
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(config.smtpUsername(), config.smtpPassword());
            }
         });
         
         var m = new MimeMessage(session);
         m.setFrom(new InternetAddress(config.smtpUsername()));
         m.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.toEmail()));
         m.setSubject("[Troostwijk] " + title);
         m.setText(msg);
         m.setSentDate(new Date());
         if (prio > 0) {
            m.setHeader("X-Priority", "1");
            m.setHeader("Importance", "High");
         }
         Transport.send(m);
         log.info("Email notification sent: " + title);
      } catch (Exception e) {
         log.info("Email notification failed: " + e);
      }
   }
   
   private record Config(
           boolean useDesktop,
           boolean useEmail,
           String smtpUsername,
           String smtpPassword,
           String toEmail
   ) {
      
      static Config parse(String cfg) {
         if ("desktop".equalsIgnoreCase(cfg)) {
            return new Config(true, false, null, null, null);
         } else if (cfg.startsWith("smtp:")) {
            var parts = cfg.split(":", 4);
            if (parts.length != 4)
               throw new IllegalArgumentException("Email config must be 'smtp:username:password:toEmail'");
            return new Config(true, true, parts[1], parts[2], parts[3]);
         }
         throw new IllegalArgumentException("Config must be 'desktop' or 'smtp:username:password:toEmail'");
      }
   }
}
