const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
	const Email = sequelize.define(
		"email",
		{
			id: {
				type: DataTypes.INTEGER,
				autoIncrement: true,
				primaryKey: true,
			},
			creation: { type: DataTypes.DATE, allowNull: false },
			modified: { type: DataTypes.DATE, allowNull: false },
			modified_by: { type: DataTypes.INTEGER, allowNull: false },
			owner: { type: DataTypes.INTEGER, allowNull: false },
			enabled: { type: DataTypes.BOOLEAN, allowNull: false },

			name: { type: DataTypes.STRING(50), allowNull: false, unique: true },
			domain_name: { type: DataTypes.STRING(50), allowNull: false, unique: true },
			email_server: { type: DataTypes.STRING(150), allowNull: true },
			use_imap: { type: DataTypes.BOOLEAN, allowNull: true },
			use_ssl: { type: DataTypes.BOOLEAN, allowNull: true },
			use_starttls: { type: DataTypes.BOOLEAN, allowNull: true },
			incoming_port: { type: DataTypes.INTEGER, allowNull: true },
			attachment_limit: { type: DataTypes.INTEGER, allowNull: true },
			smtp_server: { type: DataTypes.STRING(150), allowNull: true },
			use_tls: { type: DataTypes.BOOLEAN, allowNull: true },
			use_ssl_for_outgoing: { type: DataTypes.BOOLEAN, allowNull: true },
			smtp_port: { type: DataTypes.INTEGER, allowNull: true },

			company_id: { type: DataTypes.INTEGER, allowNull: false },
		},
		{
			tableName: "emails",
		},
		{
			freezeTableName: true,
		}
	);

	/**
	 * Associates the Email model with other models.
	 * @param {object} models - The models to associate with.
	 */
	Email.associate = (models) => {
		Email.hasMany(models.EmailAccount, { foreignKey: "email_id", as: "emailaccounts" });

		Email.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });

		Email.belongsTo(models.User, { foreignKey: "modified_by", as: "modifier" });
	};

	return Email;
};
