/**
 *  Copyright © 2025, Luis Andrés Lange <https://javacomm.net>
 *
 *  Previously released under Apache License 2.0; now licensed under MPL 2.0.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *  ----------------------------------------------------------------------------
 *
 *  Exhibit B - "Incompatible With Secondary Licenses" Notice
 *
 *  This Source Code Form is "Incompatible With Secondary Licenses",
 *  as defined by the Mozilla Public License, v. 2.0.
 *
 *  In short:
 *  - This file may be used, modified, and distributed under MPL 2.0 only.
 *  - It may NOT be relicensed under GPL, LGPL, AGPL, or any other Secondary License.
 *
 *  Rationale:
 *  - Ensures that the code remains MPL-2.0.
 *  - Avoids legal conflicts with GPL-licensed libraries (e.g., VideoLAN).
 *  - Maximizes usability for commercial and security-critical applications.
 *
 */
package net.javacomm.server;

import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import javax.naming.NamingException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.javacomm.database.DatabaseException;
import net.javacomm.database.WebdatabaseImpl;
import net.javacomm.database.entity.Config;
import net.javacomm.multilingual.MultilingualString;
import net.javacomm.multilingual.schema.ISO639;
import net.javacomm.multilingual.schema.KEY;
import net.javacomm.share.Constants;



public final class Mailsender {

  private final static Logger log = LogManager.getLogger(Mailsender.class);
  private static WebdatabaseImpl databaseservice;

  private Mailsender() {
    // Verbindung zum Mailserver
  }



  /**
   * 
   * @param recipientMail
   *                         an diese Mailadresse wird gesendet
   * @param uid
   *                         dieser Anwender wird angeschrieben. <b>uid</b> ist
   *                         ein Teil der Bestätigungs-URL.
   * @param neues_passwort
   *                         das neue Passwort. <b>Passwort</b> ist ein Teil der
   *                         Bestätigungs-URL.
   * @param lang
   *                         die Sprachkennung ist ein Teil der Bestätigungs-URL.
   * @param confirmation_key
   *                         der Bestätigungsschlüssel wird benötigt, wenn ein
   *                         altes Passort durch ein neues ersetzt wird.
   *                         <b>confirmation_key</b> darf {@code null} sein.
   * 
   */
  public static void sendMail(String recipientMail, String uid, String neues_passwort, String lang,
      String confirmation_key) throws DatabaseException {
    try {
      databaseservice = (WebdatabaseImpl) WebdatabaseImpl.getInstance();
      Config config = databaseservice.fetchConfig();
      Session mailSession = databaseservice.getMailsession(config);
      Message message = new MimeMessage(mailSession);
      if (config.getMailSmtpUser() == null) {
        log.warn(
            "Eine eMail kann nicht gesendet werden, weil es keinen SMTP-User gleich gültigen Versender gibt."
        );
        log.info("In der Tabelle TB_CONFIG muss ein Absender stehen.");
        return;
      }
      InternetAddress from = new InternetAddress(config.getMailSmtpUser());
      message.setFrom(from);
      message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientMail));
      MultilingualString betreff = new MultilingualString(KEY.SERVER_MAIL_BETREFF, ISO639.fromValue(lang));
      message.setSubject(betreff.toString());
      // richtige UID und password setzen

      MultilingualString mail = new MultilingualString(KEY.SERVER_MAIL_ERSTANMELDUNG, ISO639.fromValue(lang));

      String neuerwert = mail.toString().replace("XXX", uid);
      String neuerwert2 = neuerwert.replace("YYY", neues_passwort);

      if (confirmation_key == null) {
        message.setText(neuerwert2);
        Transport.send(message);
        // kein neues Passwort
        return;
      }
      StringBuilder buffer = new StringBuilder(neuerwert2);

      buffer.append("\r\n");
      buffer.append("\r\n\r\n");
      MultilingualString mailDasNeuePasswort = new MultilingualString(
          KEY.SERVER_MAIL_DAS_NEUE_PASSWORT, ISO639.fromValue(lang)
      );
      buffer.append(mailDasNeuePasswort.toString());
      buffer.append("\r\n\r\n");
      buffer.append(Constants.PROTOCOL);
      buffer.append(config.getDomain());
      buffer.append("/javacommserver/reset/password/");
      buffer.append(uid);
      buffer.append("/");
      buffer.append(confirmation_key);
      buffer.append("/");
      buffer.append(lang);
      buffer.append("\r\n\r\n");
      MultilingualString mailDasAltePassword = new MultilingualString(
          KEY.SERVER_MAIL_DAS_ALTE_PASSWORT, ISO639.fromValue(lang)
      );
      buffer.append(mailDasAltePassword);
      message.setText(buffer.toString());
      Transport.send(message);
      return;
    }
    catch (NamingException | MessagingException e) {
      log.error(e.getMessage(), e);
    }

  }

}
