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


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


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


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


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


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



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


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



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



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



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





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


    db.users.hasMany(db.friendships, {
      as: 'friendships_requester',
      foreignKey: {
          name: 'requesterId',
      },
      constraints: false,
    });

    db.users.hasMany(db.friendships, {
      as: 'friendships_addressee',
      foreignKey: {
          name: 'addresseeId',
      },
      constraints: false,
    });


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


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


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



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


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


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


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


    db.users.hasMany(db.user_uploads, {
      as: 'user_uploads_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;
}

