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.requisitions, {
      as: 'requisitions_requester',
      foreignKey: {
          name: 'requesterId',
      },
      constraints: false,
    });


    db.users.hasMany(db.approval_steps, {
      as: 'approval_steps_assigned_approver',
      foreignKey: {
          name: 'assigned_approverId',
      },
      constraints: false,
    });


    db.users.hasMany(db.procurement_cases, {
      as: 'procurement_cases_owner',
      foreignKey: {
          name: 'ownerId',
      },
      constraints: false,
    });




    db.users.hasMany(db.supplier_diligence_checks, {
      as: 'supplier_diligence_checks_checked_by',
      foreignKey: {
          name: 'checked_byId',
      },
      constraints: false,
    });





    db.users.hasMany(db.offer_scores, {
      as: 'offer_scores_scored_by',
      foreignKey: {
          name: 'scored_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.awards, {
      as: 'awards_awarded_by',
      foreignKey: {
          name: 'awarded_byId',
      },
      constraints: false,
    });




    db.users.hasMany(db.goods_receipt_notes, {
      as: 'goods_receipt_notes_received_by',
      foreignKey: {
          name: 'received_byId',
      },
      constraints: false,
    });



    db.users.hasMany(db.service_acceptance_notes, {
      as: 'service_acceptance_notes_accepted_by',
      foreignKey: {
          name: 'accepted_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.discrepancy_cases, {
      as: 'discrepancy_cases_reported_by',
      foreignKey: {
          name: 'reported_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.archive_items, {
      as: 'archive_items_archived_by',
      foreignKey: {
          name: 'archived_byId',
      },
      constraints: false,
    });


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


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


    db.users.hasMany(db.audit_events, {
      as: 'audit_events_actor',
      foreignKey: {
          name: 'actorId',
      },
      constraints: false,
    });


    db.users.hasMany(db.export_jobs, {
      as: 'export_jobs_requested_by',
      foreignKey: {
          name: 'requested_byId',
      },
      constraints: false,
    });


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



//end loop



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

    db.users.belongsTo(db.organizations, {
      as: 'organizations',
      foreignKey: {
        name: 'organizationsId',
      },
      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;
}

