const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');

module.exports = function(sequelize, DataTypes) {
  const users = sequelize.define(
    'users',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

firstName: {
        type: DataTypes.TEXT,
      
      

      },

lastName: {
        type: DataTypes.TEXT,
      
      

      },

phoneNumber: {
        type: DataTypes.TEXT,
      
      

      },

email: {
        type: DataTypes.TEXT,
      
      

      },

disabled: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

password: {
        type: DataTypes.TEXT,
      
      

      },

emailVerified: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

emailVerificationToken: {
        type: DataTypes.TEXT,
      
      

      },

emailVerificationTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

passwordResetToken: {
        type: DataTypes.TEXT,
      
      

      },

passwordResetTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

provider: {
        type: DataTypes.TEXT,
      
      

      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  users.associate = (db) => {

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions_filter',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });


/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity





    db.users.hasMany(db.system_parameters, {
      as: 'system_parameters_lastUpdatedByUser',
      foreignKey: {
          name: 'lastUpdatedByUserId',
      },
      constraints: false,
    });





    db.users.hasMany(db.fiscal_periods, {
      as: 'fiscal_periods_closedByUser',
      foreignKey: {
          name: 'closedByUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.fiscal_periods, {
      as: 'fiscal_periods_lockedByUser',
      foreignKey: {
          name: 'lockedByUserId',
      },
      constraints: false,
    });







    db.users.hasMany(db.employee_documents, {
      as: 'employee_documents_uploadedByUser',
      foreignKey: {
          name: 'uploadedByUserId',
      },
      constraints: false,
    });


    db.users.hasMany(db.time_records, {
      as: 'time_records_modifiedByUser',
      foreignKey: {
          name: 'modifiedByUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.time_records, {
      as: 'time_records_approvedByUser',
      foreignKey: {
          name: 'approvedByUserId',
      },
      constraints: false,
    });


    db.users.hasMany(db.biometric_imports, {
      as: 'biometric_imports_importedByUser',
      foreignKey: {
          name: 'importedByUserId',
      },
      constraints: false,
    });




    db.users.hasMany(db.leave_applications, {
      as: 'leave_applications_approvedByUser',
      foreignKey: {
          name: 'approvedByUserId',
      },
      constraints: false,
    });




    db.users.hasMany(db.payroll_runs, {
      as: 'payroll_runs_approvedByUser',
      foreignKey: {
          name: 'approvedByUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.payroll_runs, {
      as: 'payroll_runs_postedByUser',
      foreignKey: {
          name: 'postedByUserId',
      },
      constraints: false,
    });



    db.users.hasMany(db.bank_files, {
      as: 'bank_files_generatedByUser',
      foreignKey: {
          name: 'generatedByUserId',
      },
      constraints: false,
    });



    db.users.hasMany(db.journal_entries, {
      as: 'journal_entries_postedByUser',
      foreignKey: {
          name: 'postedByUserId',
      },
      constraints: false,
    });





    db.users.hasMany(db.ap_payments, {
      as: 'ap_payments_createdByUser',
      foreignKey: {
          name: 'createdByUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.ap_payments, {
      as: 'ap_payments_approvedByUser',
      foreignKey: {
          name: 'approvedByUserId',
      },
      constraints: false,
    });






    db.users.hasMany(db.job_requisitions, {
      as: 'job_requisitions_approvedByManagerUser',
      foreignKey: {
          name: 'approvedByManagerUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.job_requisitions, {
      as: 'job_requisitions_approvedByHrUser',
      foreignKey: {
          name: 'approvedByHrUserId',
      },
      constraints: false,
    });



    db.users.hasMany(db.approval_requests, {
      as: 'approval_requests_requestedByUser',
      foreignKey: {
          name: 'requestedByUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.approval_requests, {
      as: 'approval_requests_approvedByUser',
      foreignKey: {
          name: 'approvedByUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.approval_requests, {
      as: 'approval_requests_rejectedByUser',
      foreignKey: {
          name: 'rejectedByUserId',
      },
      constraints: false,
    });


    db.users.hasMany(db.notifications, {
      as: 'notifications_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.export_requests, {
      as: 'export_requests_requestedByUser',
      foreignKey: {
          name: 'requestedByUserId',
      },
      constraints: false,
    });

    db.users.hasMany(db.export_requests, {
      as: 'export_requests_approvedByUser',
      foreignKey: {
          name: 'approvedByUserId',
      },
      constraints: false,
    });


    db.users.hasMany(db.password_histories, {
      as: 'password_histories_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.refresh_tokens, {
      as: 'refresh_tokens_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.audit_logs, {
      as: 'audit_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



//end loop



    db.users.belongsTo(db.roles, {
      as: 'app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      constraints: false,
    });



    db.users.hasMany(db.file, {
      as: 'avatar',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: db.users.getTableName(),
        belongsToColumn: 'avatar',
      },
    });


    db.users.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.users.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };


    users.beforeCreate((users, options) => {
        users = trimStringFields(users);

    if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
        users.emailVerified = true;

        if (!users.password) {
            const password = crypto
                .randomBytes(20)
                .toString('hex');

            const hashedPassword = bcrypt.hashSync(
            password,
            config.bcrypt.saltRounds,
        );

            users.password = hashedPassword
            }
        }
    });

  users.beforeUpdate((users, options) => {
    users = trimStringFields(users);
  });
  

  return users;
};


function trimStringFields(users) {
  users.email = users.email.trim();

  users.firstName = users.firstName
    ? users.firstName.trim()
    : null;

  users.lastName = users.lastName
    ? users.lastName.trim()
    : null;

  return users;
}

