export const login = [
    {
        id: 'marketingLoginLambda',
        name: 'Marketing Login Lambda',
        method: 'POST',
        description: '',
        route: '/v3/api/custom/lambda/marketing-login',
        inputs: [
          { name: 'email', type: 'body', rules: 'required', dataType: 'String' },
          { name: 'password', type: 'body', rules: 'required', dataType: 'String' },
          { name: 'role', type: 'body', rules: 'required', dataType: 'String' },
          { name: 'is_refresh', type: 'body', rules: '', dataType: 'Boolean' }
        ],
        response: [
          { id: 'error', key: 'error', value: 'false', valueType: 'Boolean', parent: '' },
          { id: 'role', key: 'role', value: 'admin', valueType: 'String', parent: '' },
          { id: 'token', key: 'token', value: '', valueType: 'String', parent: '' },
          { id: 'refresh_token', key: 'refresh_token', value: '', valueType: 'String', parent: '' },
          { id: 'expire_at', key: 'expire_at', value: '', valueType: 'Number', parent: '' },
          { id: 'user_id', key: 'user_id', value: '', valueType: 'String', parent: '' },
          { id: 'two_factor_enabled', key: 'two_factor_enabled', value: '', valueType: 'Boolean', parent: '' }
        ],
        code: `app.post("/v3/api/custom/lambda/marketing-login", middlewares, async function (req, res) {
          try {
            let service = new AuthService();
            let refreshToken = undefined;
            const needRefreshToken = req.body.is_refresh ? true : false;
      
            const { email, password, role } = req.body;
            const validationResult = await ValidationService.validateInputMethod(
              {
                email: "required",
                password: "required",
                role: "required"
              },
              {
                email: "email is missing",
                password: "password is missing",
                role: "role is missing"
              },
              req
            );
            if (validationResult.error) return res.status(400).json(validationResult);
      
            logService.log(req.projectId, email, password);
            const result = await service.marketingLogin(req.sdk, req.projectId, email, password, role);
      
            if (typeof result == "string") {
              return res.status(403).json({
                error: true,
                message: result
              });
            }
      
            if (!result.status) {
              return res.status(403).json({
                error: true,
                message: "Your account is disabled"
              });
            }
      
            if (!result.verify) {
              return res.status(403).json({
                error: true,
                message: "Your email is not verified"
              });
            }
      
            //TODO: Use the secret from project
            if (needRefreshToken) {
              refreshToken = JwtService.createAccessToken(
                {
                  user_id: result.id,
                  role: role
                },
                config.refresh_jwt_expire,
                config.jwt_key
              );
              let expireDate = new Date();
              expireDate.setSeconds(expireDate.getSeconds() + config.refresh_jwt_expire);
              await service.saveRefreshToken(req.sdk, req.projectId, result.id, refreshToken, expireDate);
            }
            return res.status(200).json({
              error: false,
              role,
              token: JwtService.createAccessToken(
                {
                  user_id: result.id,
                  role
                },
                config.jwt_expire,
                config.jwt_key
              ),
              refresh_token: refreshToken,
              expire_at: config.jwt_expire,
              user_id: result.id,
              two_factor_enabled: result.two_factor_authentication === 1 ? true : false
            });
          } catch (err) {
            console.error(err);
            res.status(403).json({
              error: true,
              message: err.message
            });
          }
        });`,
        doc: '',
        unit: '',
        protected: true,
        authorizedRoles: [],
        imports: ``,
        type: 'lambda',
        group: 'login'
      },
      {
        id: 'loginLambda',
        name: 'Login Lambda',
        method: 'POST',
        description: '',
        route: '/v3/api/custom/lambda/login',
        inputs: [
          { name: 'email', type: 'body', rules: 'required', dataType: 'String' },
          { name: 'password', type: 'body', rules: 'required', dataType: 'String' },
          { name: 'role', type: 'body', rules: 'required', dataType: 'String' },
          { name: 'is_refresh', type: 'body', rules: '', dataType: 'Boolean' }
        ],
        response: [
          { id: 'error', key: 'error', value: 'false', valueType: 'Boolean', parent: '' },
          { id: 'role', key: 'role', value: 'role', valueType: 'String', parent: '' },
          { id: 'token', key: 'token', value: 'JwtService.createAccessToken({ user_id: result.id, role }, config.jwt_expire, config.jwt_key)', valueType: 'String', parent: '' },
          { id: 'refresh_token', key: 'refresh_token', value: 'refreshToken', valueType: 'String', parent: '' },
          { id: 'expire_at', key: 'expire_at', value: 'config.jwt_expire', valueType: 'Number', parent: '' },
          { id: 'user_id', key: 'user_id', value: 'result.id', valueType: 'String', parent: '' },
          { id: 'first_name', key: 'first_name', value: 'result.first_name ?? ""', valueType: 'String', parent: '' },
          { id: 'last_name', key: 'last_name', value: 'result.last_name ?? ""', valueType: 'String', parent: '' },
          { id: 'photo', key: 'photo', value: 'result.photo ?? ""', valueType: 'String', parent: '' },
          { id: 'two_factor_enabled', key: 'two_factor_enabled', value: 'result.two_factor_authentication === 1 ? true : false', valueType: 'Boolean', parent: '' }
        ],
        code: `app.post("/v3/api/custom/lambda/login", middlewares, async function (req, res) {
          try {
            let service = new AuthService();
            let refreshToken = undefined;
            const needRefreshToken = req.body.is_refresh ? true : false;
      
            const { email, password, role } = req.body;
            const validationResult = await ValidationService.validateInputMethod(
              {
                email: "required",
                password: "required",
                role: "required"
              },
              {
                email: "email is missing",
                password: "password is missing",
                role: "role is missing"
              },
              req
            );
            if (validationResult.error) return res.status(400).json(validationResult);
      
            logService.log(req.projectId, email, password);
            const result = await service.login(req.sdk, req.projectId, email, password, role);
      
            if (typeof result == "string") {
              return res.status(403).json({
                error: true,
                message: result
              });
            }
      
            if (!result.status) {
              return res.status(403).json({
                error: true,
                message: "Your account is disabled"
              });
            }
      
            if (!result.verify) {
              return res.status(403).json({
                error: true,
                message: "Your email is not verified"
              });
            }
      
            //TODO: Use the secret from project
            if (needRefreshToken) {
              refreshToken = JwtService.createAccessToken(
                {
                  user_id: result.id,
                  role: role
                },
                config.refresh_jwt_expire,
                config.jwt_key
              );
              let expireDate = new Date();
              expireDate.setSeconds(expireDate.getSeconds() + config.refresh_jwt_expire);
              await service.saveRefreshToken(req.sdk, req.projectId, result.id, refreshToken, expireDate);
            }
            return res.status(200).json({
              error: false,
              role,
              token: JwtService.createAccessToken(
                {
                  user_id: result.id,
                  role
                },
                config.jwt_expire,
                config.jwt_key
              ),
              refresh_token: refreshToken,
              expire_at: config.jwt_expire,
              user_id: result.id,
              first_name: result.first_name ?? "",
              last_name: result.last_name ?? "",
              photo: result.photo ?? "",
              two_factor_enabled: result.two_factor_authentication === 1 ? true : false
            });
          } catch (err) {
            console.error(err);
            res.status(403).json({
              error: true,
              message: err.message
            });
          }
        });`,
        doc: '',
        unit: '',
        protected: true,
        authorizedRoles: [],
        imports: ``,
        type: 'lambda',
        group: 'login'
      }
      
      
]

export const loginImports = `

const AuthService = require("../../../services/AuthService");
const JwtService = require("../../services/JwtService");
const ProjectMiddleware = require("../../../middleware/ProjectMiddleware");
const UrlMiddleware = require("../../../middleware/UrlMiddleware");
const HostMiddleware = require("../../../middleware/HostMiddleware");
const LogMiddleware = require("../../../middleware/LogMiddleware");
const PermissionMiddleware = require("../../../middleware/PermissionMiddleware");
const RateLimitMiddleware = require("../../../middleware/RateLimitMiddleware");
const DevLogService = require("../../../services/DevLogService");
const ValidationService = require("../../../services/ValidationService");

const middlewares = [
  ProjectMiddleware,
  UrlMiddleware,
  // HostMiddleware,
  // PermissionMiddleware,
  RateLimitMiddleware,
  LogMiddleware
  // UsageMiddleware
  // CheckProjectMiddleware,
  // AnalyticMiddleware,
  // RoleMiddleware
];

let logService = new DevLogService();

const config = require("../../../config");

`