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.tutor_profiles, {
      as: 'tutor_profiles_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


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








    db.users.hasMany(db.bookings, {
      as: 'bookings_learner',
      foreignKey: {
          name: 'learnerId',
      },
      constraints: false,
    });

    db.users.hasMany(db.bookings, {
      as: 'bookings_tutor',
      foreignKey: {
          name: 'tutorId',
      },
      constraints: false,
    });


    db.users.hasMany(db.conversations, {
      as: 'conversations_tutor',
      foreignKey: {
          name: 'tutorId',
      },
      constraints: false,
    });

    db.users.hasMany(db.conversations, {
      as: 'conversations_learner',
      foreignKey: {
          name: 'learnerId',
      },
      constraints: false,
    });


    db.users.hasMany(db.messages, {
      as: 'messages_sender',
      foreignKey: {
          name: 'senderId',
      },
      constraints: false,
    });

    db.users.hasMany(db.messages, {
      as: 'messages_receiver',
      foreignKey: {
          name: 'receiverId',
      },
      constraints: false,
    });


    db.users.hasMany(db.reviews, {
      as: 'reviews_tutor',
      foreignKey: {
          name: 'tutorId',
      },
      constraints: false,
    });

    db.users.hasMany(db.reviews, {
      as: 'reviews_learner',
      foreignKey: {
          name: 'learnerId',
      },
      constraints: false,
    });



    db.users.hasMany(db.disputes, {
      as: 'disputes_opened_by',
      foreignKey: {
          name: 'opened_byId',
      },
      constraints: false,
    });

    db.users.hasMany(db.disputes, {
      as: 'disputes_resolved_by',
      foreignKey: {
          name: 'resolved_byId',
      },
      constraints: false,
    });


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



    db.users.hasMany(db.admin_audit_logs, {
      as: 'admin_audit_logs_admin_user',
      foreignKey: {
          name: 'admin_userId',
      },
      constraints: false,
    });


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


    db.users.hasMany(db.invites, {
      as: 'invites_sender',
      foreignKey: {
          name: 'senderId',
      },
      constraints: false,
    });

    db.users.hasMany(db.invites, {
      as: 'invites_receiver',
      foreignKey: {
          name: 'receiverId',
      },
      constraints: false,
    });



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


    db.users.hasMany(db.community_posts, {
      as: 'community_posts_author',
      foreignKey: {
          name: 'authorId',
      },
      constraints: false,
    });


    db.users.hasMany(db.community_comments, {
      as: 'community_comments_author',
      foreignKey: {
          name: 'authorId',
      },
      constraints: false,
    });


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


    db.users.hasMany(db.community_reports, {
      as: 'community_reports_reporter',
      foreignKey: {
          name: 'reporterId',
      },
      constraints: false,
    });

    db.users.hasMany(db.community_reports, {
      as: 'community_reports_resolved_by',
      foreignKey: {
          name: 'resolved_byId',
      },
      constraints: false,
    });



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


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



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


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


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


    db.users.hasMany(db.study_group_posts, {
      as: 'study_group_posts_author',
      foreignKey: {
          name: 'authorId',
      },
      constraints: false,
    });


    db.users.hasMany(db.study_group_messages, {
      as: 'study_group_messages_sender',
      foreignKey: {
          name: 'senderId',
      },
      constraints: false,
    });


    db.users.hasMany(db.study_group_resources, {
      as: 'study_group_resources_added_by',
      foreignKey: {
          name: 'added_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.live_events, {
      as: 'live_events_host',
      foreignKey: {
          name: 'hostId',
      },
      constraints: false,
    });


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


    db.users.hasMany(db.certificates, {
      as: 'certificates_learner',
      foreignKey: {
          name: 'learnerId',
      },
      constraints: false,
    });

    db.users.hasMany(db.certificates, {
      as: 'certificates_tutor',
      foreignKey: {
          name: 'tutorId',
      },
      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;
}

