const bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
	const Drivers = sequelize.define(
		'Drivers',
		{
			id: {
				type: DataTypes.UUID,
				defaultValue: DataTypes.UUIDV4,
				allowNull: false,
				primaryKey: true,
			},
			email_address: {
				type: DataTypes.STRING,
				allowNull: false,
				unique: true,
			},
			password: {
				type: DataTypes.STRING,
				allowNull: false,
			},
			driver_name: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			conductor_name: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			shuttle_number: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			plate_number: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			driver_photo: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			vehicle_photo: {
				type: DataTypes.STRING,
				allowNull: true,
			},
			status: {
				type: DataTypes.ENUM('online', 'offline'),
				allowNull: false,
				defaultValue: 'offline',
			},
			createdAt: {
				allowNull: false,
				type: DataTypes.DATE,
				defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
			},
			updatedAt: {
				allowNull: false,
				type: DataTypes.DATE,
				defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
			},
		},
		{
			tableName: 'drivers',
			timestamps: true,
			hooks: {
				beforeCreate: async (driver) => {
					if (driver.changed('password')) {
						driver.password = await bcrypt.hash(driver.password, 10);
					}
				},
				beforeUpdate: async (driver) => {
					if (driver.changed('password')) {
						driver.password = await bcrypt.hash(driver.password, 10);
					}
				},
			},
		},
	);

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

	return Drivers;
};
