const bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
	const ConventionUsers = sequelize.define(
		'ConventionUsers',
		{
			id: {
				type: DataTypes.UUID,
				defaultValue: DataTypes.UUIDV4,
				allowNull: false,
				primaryKey: true,
			},
			first_name: {
				type: DataTypes.STRING,
				allowNull: false,
			},
			middle_name: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			last_name: {
				type: DataTypes.STRING,
				allowNull: false,
			},
			convention_center: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			event_id: {
				type: DataTypes.UUID,
				allowNull: true,
			},
			createdAt: {
				type: DataTypes.DATE,
				allowNull: false,
			},
			email_address: {
				type: DataTypes.STRING,
				allowNull: false,
				unique: true,
			},
			password: {
				type: DataTypes.STRING,
				allowNull: false,
			},
		},
		{
			tableName: 'convention_users',
			timestamps: true,
			hooks: {
				beforeCreate: async (convention) => {
					if (convention.changed('password')) {
						convention.password = await bcrypt.hash(convention.password, 10);
					}
				},
				beforeUpdate: async (convention) => {
					if (convention.changed('password')) {
						convention.password = await bcrypt.hash(convention.password, 10);
					}
				},
			},
		},
	);

	ConventionUsers.prototype.validatePassword = async function (password) {
		return bcrypt.compare(password, this.password);
	};

	ConventionUsers.associate = (models) => {
		ConventionUsers.belongsTo(models.Events, {
			foreignKey: 'event_id',
			as: 'event',
		});
	};

	return ConventionUsers;
};
