/**
 *  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 static net.javacomm.protocol.HEADER.CONFIRM;
import static net.javacomm.protocol.HEADER.ERROR;
import static net.javacomm.protocol.HEADER.REQUEST;
import static net.javacomm.protocol.HEADER.RESPONSE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.FormParam;
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 org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.javacomm.database.DatabaseException;
import net.javacomm.database.WebdatabaseImpl;
import net.javacomm.facade.DatabaseService;
import net.javacomm.multilingual.MultilingualString;
import net.javacomm.multilingual.schema.ISO639;
import net.javacomm.multilingual.schema.KEY;
import net.javacomm.protocol.Command;
import net.javacomm.protocol.Protocol;
import net.javacomm.protocol.SIGNIN;
import net.javacomm.server.Mailsender;



@Path("/signin")
public class Signinrs {

  private final Logger log = LogManager.getLogger(Signinrs.class);

  public Signinrs() {}



  /**
   * 
   * @param email
   *                   E-Mail vom Benutzer
   * @param lang
   *                   diese Sprache
   * @param webconfirm
   *                   {@code true}, wenn die Anfrage von der Homepage kommt
   * 
   * @return SIGNIN-Response
   * 
   */
  private SIGNIN signIn(String email, String lang, boolean webconfirm) throws DatabaseException {
    DatabaseService databaseservice = WebdatabaseImpl.getInstance();
    SIGNIN request = new SIGNIN();
    request.setCommand(Command.SIGNIN);
    request.setHeader(REQUEST);
    request.setDataset(Protocol.DATASET);
    request.setEmail(email == null ? "" : email);
    SIGNIN response = databaseservice.signinUser(request.getEmail(), webconfirm);

    if (CONFIRM == response.getHeader()) {
      // Ein neuer Anwender wird registriert
      Mailsender.sendMail(response.getEmail(), response.getPassword(), lang, null);
      MultilingualString text = webconfirm
          ? new MultilingualString(KEY.SERVER_WEBCONFIRM_PASSWORT, ISO639.fromValue(lang))
          : new MultilingualString(KEY.SERVER_CONFIRM_PASSWORT, ISO639.fromValue(lang));
      response.setText(text.toString());
      return response;
    }
    else if (RESPONSE == response.getHeader()) {
      // ein neues PASSWORD wird angefordert

      MultilingualString text = new MultilingualString(response.getMultilingualkey(), ISO639.fromValue(lang));
      response.setText(text.toString());
      Mailsender
          .sendMail(response.getEmail(), response.getNeuesPassword(), lang, response.getConfirmationKey());
      databaseservice.updateConfirmationFlag(null, response.getEmail(), 1);
      return response;

    }
    else if (ERROR == response.getHeader()) {
      MultilingualString text = new MultilingualString(response.getMultilingualkey(), ISO639.fromValue(lang));
      response.setText(text.toString());
    }

    return response;
  }



  /**
   * Ein neuer Anwender möchte sich einschreiben.
   * 
   * @param email
   *                   der Anmelder
   * @param lang
   *                   die Spracheinstellung vom Anwender. Sie ist als
   *                   Pfadparameter in der Antwortmail enthalten
   * @param webconfirm
   *                   {@code true}, die Anfrage kommt von der Homepage, sonst vom
   *                   Client
   * 
   * @return JSON-String als encoded SIGNIN
   * 
   * @throws WebApplicationException
   */
  @POST
  @Produces(MediaType.APPLICATION_JSON)
  public String subscribe(@FormParam("email") String email,
      @DefaultValue("en") @FormParam("lang") String lang,
      @DefaultValue("false") @FormParam("webconfirm") boolean webconfirm) {

    try {
      return signIn(email, lang, webconfirm).toString();
    }
    catch (DatabaseException e) {
      log.error(e.getMessage(), e);
      throw new WebApplicationException();
    }
  }

}
