fcf.module({
  name: "fcfSimpleAuthorization:controllers/login-by-email.js",
  dependencies: ["fcf:NServer/NControllers/Controller.js"],
  module: function(Controller){
    var Namespace = fcf.prepareObject(fcf, "packages/fcfSimpleAuthorization/controllers");

    fcf.addException("FCF_SIMPLE_AUTHORIZATION_INVALID_TOKEN", "The authorization token is invalid");

    Namespace.LoginByEmail = class LoginByEmail extends Controller {
      action(a_request) {
        let self = this;

        if (!fcf.application.getConfiguration().fcfSimpleAuthorization_enableLoginByEmail) {
          a_request.setErrorPage(new fcf.Exception("OPERATION_NOT_SUPPORTED"));
          return;
        }

        return fcf.actions()
        .then(()=>{
          return fcf.application.getStorage().query(
            "SELECT user FROM ___fcfSimpleAuthorization___login_by_email WHERE token = ${1}",
            [fcf.getContext().route.args.token],
            { roles: ["root"] }
          );
          
        })
        .then((a_records)=>{
          if (fcf.empty(a_records[0]))
            throw new fcf.Exception("FCF_SIMPLE_AUTHORIZATION_INVALID_TOKEN");

          let user = a_records[0][0].user;

          if (!user.active)
            throw new fcf.Exception("FCF_LOGIN_INVALID_USER_BLOCKED");
          if (!fcf.application.getConfiguration().loginUncreatedUser && !user.initialized)
            throw new fcf.Exception("FCF_LOGIN_INVALID_USER_NOT_CREATED");

          let sessionId = fcf.randStr(64);
          return fcf.application.getStorage().query(
            "DELETE FROM ___fcfSimpleAuthorization___login_by_email WHERE token = ${1};" + 
            "UPDATE ___fcf___users SET last_login_attempt = ${2} WHERE id = ${3};" +
            "INSERT INTO ___fcf___sessions (session_id, user_id, start, last) VALUES(${4}, ${5}, ${6}, ${7})",
            [ fcf.getContext().route.args.token,
              fcf.dateFormat(new Date(), "Y-m-d H:i:s") , user.id,
              sessionId, user.id, fcf.dateFormat(new Date(), "Y-m-d H:i:s"), fcf.dateFormat(new Date(), "Y-m-d H:i:s")
            ],
            { roles: ["root"] }
          )
          .then(()=>{
            return sessionId;
          })
        })
        .then((a_sessionId)=>{
          fcf.getContext().session.id = a_sessionId;
          fcf.saveContext(a_request);
          a_request.redirect('/');
        })
        .catch((a_error)=>{
          a_request.error(a_error);
        })
      }


    };

    return Namespace.LoginByEmail;
  }
});
