const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');

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,
        allowNull: false,
        unique: true,
        validate: {
          isEmail: { msg: 'Must be a valid email address' },
          notEmpty: { msg: 'Email is required' },
        },
      },

      disabled: {
        type: DataTypes.BOOLEAN,

        allowNull: false,
        defaultValue: false,
      },

      password: {
        type: DataTypes.TEXT,
        allowNull: false,
      },

      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,
        allowNull: false,
        defaultValue: providers.LOCAL,
      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
      indexes: [
        { fields: ['email'], unique: true },
        { fields: ['app_roleId'] },
        { fields: ['deletedAt'] },
      ],
    },
  );

  users.associate = (db) => {
    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      through: 'usersCustom_permissionsPermissions',
    });

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions_filter',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      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.project_memberships, {
      as: 'project_memberships_user',
      foreignKey: {
        name: 'userId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    });

    db.users.hasMany(db.presigned_url_requests, {
      as: 'presigned_url_requests_user',
      foreignKey: {
        name: 'userId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    });

    db.users.hasMany(db.publish_events, {
      as: 'publish_events_user',
      foreignKey: {
        name: 'userId',
      },
      constraints: true,
      onDelete: 'SET NULL',
      onUpdate: 'CASCADE',
    });

    db.users.hasMany(db.access_logs, {
      as: 'access_logs_user',
      foreignKey: {
        name: 'userId',
      },
      constraints: true,
      onDelete: 'SET NULL',
      onUpdate: 'CASCADE',
    });

    //end loop

    db.users.belongsTo(db.roles, {
      as: 'app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      constraints: true,
      onDelete: 'SET NULL',
      onUpdate: 'CASCADE',
    });

    db.users.hasMany(db.file, {
      as: 'avatar',
      foreignKey: 'belongsToId',
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
      scope: {
        belongsTo: db.users.getTableName(),
        belongsToColumn: 'avatar',
      },
    });

    db.users.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.users.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };

  users.beforeCreate((users) => {
    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) => {
    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;
}
