/**
 *  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.restserver;

import jakarta.mail.MessagingException;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.naming.NamingException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.media.multipart.FormDataParam;
import net.javacomm.database.DatabaseException;
import net.javacomm.database.MailportException;
import net.javacomm.database.WebdatabaseImpl;
import net.javacomm.database.entity.Config;
import net.javacomm.database.entity.EntityUser;
import net.javacomm.database.entity.Outdated;
import net.javacomm.protocol.Benutzerstatus;
import net.javacomm.share.Constants;
import net.javacomm.transfer.TransferBenutzerkonto;
import net.javacomm.transfer.TransferConfig;
import net.javacomm.transfer.TransferOutdated;
import net.javacomm.transfer.TransferRoomfilter;
import net.javacomm.transfer.TransferUser;



@Produces(MediaType.APPLICATION_JSON)
@Path("/administrator")
public class Administrator {

  final Logger log = LogManager.getLogger(Administrator.class);
  private WebdatabaseImpl database;

  private final AdminProvider adminProvider = () -> {
    SecurityService service = new SecurityService();
    return service;
  };

  public Administrator() {
    database = (WebdatabaseImpl) WebdatabaseImpl.getInstance();
  }



  @POST
  @Path("delete/nicknames")
  @Produces(MediaType.TEXT_PLAIN)
  public boolean deleteNicknames(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "nicknames") Wrapper wrapper) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);
    return database.remainNicknames(wrapper.getStringList());
  }



  @POST
  @Path("delete/outdated")
  @Produces(MediaType.TEXT_PLAIN)
  public boolean deleteOutdated(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "outdated") Wrapper wrapper) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);
    return database.remainOutdated(wrapper.getStringList());
  }



  /**
   * Lies eine Anwenderliste mit Kontoaktivitäten aus.
   *
   *
   * @param userid
   *                 die Userid von einem Administrator
   * @param password
   *                 das zugehörige Passwort
   * @return eine Anwenderliste mit Kontoaktivitäten
   */
  @POST
  @Path("/user")
  public List<TransferUser> getUserList(@FormDataParam(value = "pseudoid") String pseudoid,
      @FormDataParam(value = "cblock") String cblock) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    ArrayList<TransferUser> liste = new ArrayList<>();
    List<EntityUser> userliste = database.readBenutzerAntraege();
    userliste.forEach(user -> {
      TransferUser item = new TransferUser();
      int status = user.getBenutzerstatus();
      Benutzerstatus benutzerstatus = Benutzerstatus.toBenutzerstatus(status);
      item.setBenutzerstatus(benutzerstatus.getStatus());
      item.setMail(user.getMail());
//      String helper = database.fetchPseudoidByUserid(user.getUid());
      // item ist ein Transferuser
//      item.setPseudoid(helper);
      item.setUserid(user.getUid());
      liste.add(item);
    });
    return liste;
  }



  /**
   * Ist der Anwender ein Administrator?
   *
   *
   * @param userid
   *               eine Pseudoid
   * @param cblock
   *               enthält das Pseudopassword und den Timestamp
   * 
   * @return HTTP 204 bei Erfolg, sonst HTTP-403 forbidden
   */
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public Response isAdministrator(@HeaderParam(value = "pseudoid") String pseudoid,
      @HeaderParam(value = "cblock") String cblock) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);
    return Response.status(Status.NO_CONTENT).build();
  }



  /**
   * Ein Benutzeraccount wird logisch gelöscht oder zurückgeholt.
   *
   *
   * @param adminid
   *                 nur ein Administrator darf die Aktion durchführen
   * @param password
   *                 Admins password
   * @param userid
   *                 der Anwender, dessen Konto gelöscht oder zurückgeholt wird
   * @param deleted
   *                 {@code true}, das Konto wird gelöscht
   *
   * @return {@code deleted}, wenn der Aufruf erfolgreich war
   */
  @POST
  @Path("/delete/logically")
  @Produces(MediaType.TEXT_PLAIN)
  public boolean logicallyDelete(@FormDataParam(value = "pseudoid") String pseudoid,
      @FormDataParam(value = "cblock") String cblock, @FormDataParam(value = "userid") String userid,
      @FormDataParam(value = "deleted") boolean deleted) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);
    try {
      database.deleteLogicUser(userid, deleted);
    }
    catch (SQLException e) {
      log.error(e.getMessage());
      throw new WebApplicationException();
    }
    return deleted;
  }



  @POST
  @Path("/read/accounts")
  @Produces(MediaType.APPLICATION_JSON)
  public List<TransferBenutzerkonto> readBenutzerkonten(@FormDataParam(value = "pseudoid") String pseudoid,
      @FormDataParam(value = "cblock") String cblock) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    ArrayList<TransferBenutzerkonto> accounts = new ArrayList<>();

    try {
      List<EntityUser> result = database.fetchUsers();
      result.forEach(entityUser -> {

        TransferBenutzerkonto transferkonto = new TransferBenutzerkonto();
        transferkonto.setLdelete(entityUser.isLdelete());
        transferkonto.setMail(entityUser.getMail());
        transferkonto.setNickname(entityUser.getNickname());
        transferkonto.setTime(entityUser.getTime());
        transferkonto.setUid(entityUser.getUid());

        accounts.add(transferkonto);

      });

    }
    catch (SQLException e) {
      log.error(e.getMessage(), e);
      throw new WebApplicationException(e);
    }
    return accounts;
  }



  /**
   * Lies die Konfigurationseinstellungen aus. Das zurückgegebene Transferobjekt
   * ist leer, aber {@code !=null}, wenn der Anwender kein Administrator ist.
   *
   *
   * @param userid
   *                 die Userid von einem Administrator
   * @param password
   *                 das zugehörige Passwort
   *
   * @return die Konfigurationseinstellungen
   * @throws SQLException
   */
  @POST
  @Path("/read/config")
  public TransferConfig readConfig(@FormDataParam(value = "pseudoid") String pseudoid,
      @FormDataParam(value = "cblock") String cblock) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    Config config;
    try {
      config = database.fetchConfig();
      TransferConfig transfer = new TransferConfig();
      transfer.setDomain(config.getDomain());
      transfer.setIsPublic(config.getIsPublic());
      transfer.setMailSmtpHost(database.getSmtpHost());
      transfer.setMailSmtpUser(database.getSmtpUser());
      transfer.setMailSmtpPort(database.getSmtpPort());
      transfer.setAdminPostfach(database.getAdminmail());
      transfer.setSmtpPasswort(database.getSmtpPassword());
      transfer.setFlipToForum(config.getFlipToForum());
      transfer.setHours(config.getHours());
      transfer.setAccount(config.getAccount());
      return transfer;
    }
    catch (DatabaseException | NamingException e) {
      Response response = Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN)
          .entity(e.getMessage()).build();
      throw new WebApplicationException(response);
    }

  }



  /**
   * Alle verbotenen Nicknames werden gelesen.
   *
   * @return eine Liste verbotener Nicknames
   */
  @GET
  @Path("/read/nicknames")
  public List<String> readNicknames() {
    return database.fetchForbiddenNicknames();
  }



  /**
   * Alle veralteten Programmversionsnummern werden gelesen.
   *
   * @return eine Liste veralterter Versionsnummern
   */
  @GET
  @Path("/read/outdated")
  public List<String> readOutdated() {
    return database.fetchOutdated();
  }



  /**
   * Returns all room filters.
   *
   * @param userid
   *                 the user ID of an administrator
   * @param password
   *                 the corresponding password
   * @return the list of filters
   */
  @POST
  @Path("/read/roomfilter")
  @Produces(MediaType.APPLICATION_JSON)
  public List<TransferRoomfilter> readRoomfilter(@FormDataParam(value = "pseudoid") String pseudoid,
      @FormDataParam(value = "cblock") String cblock) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    ArrayList<TransferRoomfilter> filterliste = new ArrayList<>();
    List<String> result = database.fetchForbiddenNames();
    result.forEach(forbidden -> {
      TransferRoomfilter roomfilter = new TransferRoomfilter();
      roomfilter.setRoomfilter(forbidden);
      filterliste.add(roomfilter);
    });
    return filterliste;
  }



  /**
   * Deletes the specified room filters.
   *
   * This operation requires administrator credentials.
   *
   * @param userid
   *                   the user ID of an administrator
   * @param password
   *                   the corresponding password
   * @param filterList
   *                   the list of filters to be deleted
   * @return a {@link Response} containing the list of deleted filters
   */
  @POST
  @Path("/remove/roomfilter")
  @Produces(MediaType.TEXT_PLAIN)
  public Response removeRoomfilter(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "filterlist") Wrapper wrapper) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    boolean done = false;
    if (wrapper == null) {
      return Response.status(Status.BAD_REQUEST).build();
    }
    List<String> filterlist = wrapper.getStringList();
    try {
      done = database.deleteForbiddenRoomfilter(filterlist);
    }
    catch (DatabaseException e) {
      Response response = Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN)
          .entity(e.getMessage()).build();
      throw new WebApplicationException(response);
    }
    return Response.ok(done).build();
  }



  /**
   *
   *
   * @param pseudoid
   *                  Pseudoid von einem Admin
   * @param password
   *                  Password von einem Admin
   * @param userliste
   *                  die Benutzerdaten enthalten den neuen Status
   *
   * @return {@code true}, alle Änderungen wurden durchgeführt; {@code false}
   *         mindestens eine Änderung wurde nicht durhcgeführt
   */
  @POST
  @Path("/benutzerstatus")
  @Produces(MediaType.TEXT_PLAIN)
  public boolean writeBenutzerstatus(@FormDataParam(value = "pseudoid") String pseudoid,
      @FormDataParam(value = "cblock") String cblock, @FormDataParam(value = "userliste") Wrapper wrapper) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    boolean done = true;
    boolean result;
    for (TransferUser tmp : wrapper.getTransferUser()) {
      result = database
          .updateBenutzerstatus(Benutzerstatus.toBenutzerstatus(tmp.getBenutzerstatus()), tmp.getUserid());
      done = done && result;
    }
    return done;
  }



  /**
   * Neue Konfigurationseinstellungen werden gespeichert.
   *
   *
   * @param userid
   *                 Userid von einem Admin
   * @param password
   *                 Password von einem Admin
   * @param config
   *                 Transferobjekt mit Konfigurationseinstellungen
   * @return {@code true}, die Einstellungen wurden übernommen
   */
  @POST
  @Path("/write/config")
  @Produces(MediaType.TEXT_PLAIN)
  public boolean writeConfig(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "config") TransferConfig config) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    Config entityConfig = new Config();
    entityConfig.setDomain(config.getDomain());
    entityConfig.setIsPublic(config.getIsPublic());
    entityConfig.setFlipToForum(
        config.getFlipToForum() < 1 || config.getFlipToForum() > 1440 ? 150 : config.getFlipToForum()
    );
    entityConfig.setHours(
        config.getHours() < Constants.MIN_DURATION_TIME || config.getHours() > Constants.MAX_DURATION_TIME
            ? Constants.MAX_DURATION_TIME
            : config.getHours()
    );
    entityConfig.setAccount(
        entityConfig.getAccount() < Constants.MIN_ACCOUNT_TIME ? Constants.MIN_ACCOUNT_TIME
            : entityConfig.getAccount()
    );
    try {
      database.updateConfig(entityConfig);
    }
    catch (DatabaseException e) {
      log.error(e.getMessage(), e);
      return false;
    }
    return true;
  }

//TODO hier geht es weiter



  @POST
  @Path("write/nicknames")
  @Produces(MediaType.TEXT_PLAIN)
  public boolean writeNicknames(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "nicknames") Wrapper wrapper) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    List<String> nicknames = wrapper.getStringList();
    return database.updateForbiddenNicknames(nicknames);
  }



  @POST
  @Path("write/outdated")
  @Produces(MediaType.TEXT_PLAIN)
  public boolean writeOutdated(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "outdated") Wrapper wrapper) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    List<TransferOutdated> outdatedlist = wrapper.getTransferOutdated();
    ArrayList<Outdated> entity = new ArrayList<>();
    for (TransferOutdated tmp : outdatedlist) {
      Outdated outdated = new Outdated();
      outdated.setProgrammversion(tmp.getProgrammversion());
      entity.add(outdated);
    }
    return database.updateOutdated(entity);
  }



  @POST
  @Path("/write/single/roomfilter")
  @Produces(MediaType.TEXT_PLAIN)
  public Response writeRoomfilter(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "filter") String filter) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    if (filter == null | filter.isEmpty()) {
      Response response = Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN)
          .entity("Invalid request parameter: 'filter' is empty. A non-empty filter name is required.")
          .build();
      throw new WebApplicationException(response);
    }
    try {
      database.addRoomfilter(List.of(filter));
      return Response.ok(filter).build();
    }
    catch (DatabaseException e) {
      log.error(e.getMessage());
      Response response = Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN)
          .entity(e.getMessage()).build();
      throw new WebApplicationException(response);
    }
  }



  /**
   * Sende eine Testmail.
   * 
   * @param userid
   *                       diese userid ist ein Administrator
   * @param password
   *                       dieses Passwort gehört zum Administrator
   * @param transferConfig
   *                       enthält Attribute für Mailing
   * 
   * @return an diese Mailadresse wurde gesendet; der Rückgabewert kann leer sein,
   *         wenn der Anfrager kein Administrator war.
   */
  @POST
  @Path("/testmail")
  @Produces(MediaType.TEXT_PLAIN)
  public Response writeTestmail(@FormParam(value = "pseudoid") String pseudoid,
      @FormParam(value = "cblock") String cblock, @FormParam(value = "host") String host,
      @FormParam(value = "user") String user, @FormParam(value = "port") Integer port,
      @FormParam(value = "smptPassword") String smptPassword,
      @FormParam(value = "adminPostfach") String adminPostfach) {

    SecurityService service = adminProvider.create();
    service.verifyAdminOrThrow(pseudoid, cblock);

    try {
      Optional<String> userid = database.fetchUserByPseudoid(pseudoid);
      String isocode = database.fetchLanguage(userid.get());
      String adminmail = database.testMail(host, user, port, smptPassword, adminPostfach, isocode);
      Response ok = Response.status(Status.OK).type(MediaType.TEXT_PLAIN).entity(adminmail).build();
      return ok;
    }
    catch (MessagingException e) {
      log.error(e.getMessage());
      Response response = Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN)
          .entity("host " + host + ", user " + user + ", port " + port + ", adminPostfach " + adminPostfach)
          .build();
      throw new WebApplicationException(response);
    }
    catch (NamingException e) {
      log.error(e.getMessage());
      Response response = Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN)
          .entity(e.getMessage()).build();
      throw new WebApplicationException(response);
    }
    catch (MailportException e) {
      log.error(e.getMessage());
//      Unprocessable Entity 422
      Response response = Response.status(422).type(MediaType.TEXT_PLAIN).entity(e.getMessage()).build();
      throw new WebApplicationException(response);

    }
  }

}
