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


    db.users.hasMany(db.teams, {
      as: 'teams_manager',
      foreignKey: {
          name: 'managerId',
      },
      constraints: false,
    });


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







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

    db.users.hasMany(db.enrollments, {
      as: 'enrollments_assigned_by',
      foreignKey: {
          name: 'assigned_byId',
      },
      constraints: false,
    });


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





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






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


    db.users.hasMany(db.knowledge_gap_assessments, {
      as: 'knowledge_gap_assessments_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.user_badges, {
      as: 'user_badges_awarded_by',
      foreignKey: {
          name: 'awarded_byId',
      },
      constraints: false,
    });


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


    db.users.hasMany(db.challenges, {
      as: 'challenges_created_by',
      foreignKey: {
          name: 'created_byId',
      },
      constraints: false,
    });


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



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


    db.users.hasMany(db.recognition_posts, {
      as: 'recognition_posts_from_user',
      foreignKey: {
          name: 'from_userId',
      },
      constraints: false,
    });

    db.users.hasMany(db.recognition_posts, {
      as: 'recognition_posts_to_user',
      foreignKey: {
          name: 'to_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.coaching_sessions, {
      as: 'coaching_sessions_coach',
      foreignKey: {
          name: 'coachId',
      },
      constraints: false,
    });

    db.users.hasMany(db.coaching_sessions, {
      as: 'coaching_sessions_coachee',
      foreignKey: {
          name: 'coacheeId',
      },
      constraints: false,
    });



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


    db.users.hasMany(db.qa_evaluations, {
      as: 'qa_evaluations_evaluator',
      foreignKey: {
          name: 'evaluatorId',
      },
      constraints: false,
    });

    db.users.hasMany(db.qa_evaluations, {
      as: 'qa_evaluations_agent',
      foreignKey: {
          name: 'agentId',
      },
      constraints: false,
    });





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




    db.users.hasMany(db.audit_events, {
      as: 'audit_events_actor',
      foreignKey: {
          name: 'actorId',
      },
      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;
}

