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.patients, {
      as: 'patients_primary_physician',
      foreignKey: {
          name: 'primary_physicianId',
      },
      constraints: false,
    });


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


    db.users.hasMany(db.medications, {
      as: 'medications_prescribed_by',
      foreignKey: {
          name: 'prescribed_byId',
      },
      constraints: false,
    });



    db.users.hasMany(db.calendar_events, {
      as: 'calendar_events_created_by_user',
      foreignKey: {
          name: 'created_by_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.reminders, {
      as: 'reminders_recipient_user',
      foreignKey: {
          name: 'recipient_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.cognitive_programs, {
      as: 'cognitive_programs_created_by_user',
      foreignKey: {
          name: 'created_by_userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.cognitive_sessions, {
      as: 'cognitive_sessions_started_by_user',
      foreignKey: {
          name: 'started_by_userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.stage_assessments, {
      as: 'stage_assessments_reviewed_by_user',
      foreignKey: {
          name: 'reviewed_by_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.voice_assistant_sessions, {
      as: 'voice_assistant_sessions_initiated_by_user',
      foreignKey: {
          name: 'initiated_by_userId',
      },
      constraints: false,
    });





    db.users.hasMany(db.alerts, {
      as: 'alerts_assigned_to_user',
      foreignKey: {
          name: 'assigned_to_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.alert_notifications, {
      as: 'alert_notifications_recipient_user',
      foreignKey: {
          name: 'recipient_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.shared_dashboard_posts, {
      as: 'shared_dashboard_posts_author_user',
      foreignKey: {
          name: 'author_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.scientific_articles, {
      as: 'scientific_articles_validated_by_user',
      foreignKey: {
          name: 'validated_by_userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.clinical_reports, {
      as: 'clinical_reports_generated_by_user',
      foreignKey: {
          name: 'generated_by_userId',
      },
      constraints: false,
    });




//end loop



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

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

