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

module.exports = (sequelize) => {
	const EmailAccount = sequelize.define(
		"emailaccount",
		{
			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 },
			email_account: { type: DataTypes.STRING(50), allowNull: false, unique: true },
			password: { type: DataTypes.STRING(150), allowNull: true },

			// fk
			email_id: { type: DataTypes.INTEGER, allowNull: true },
			company_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "emailaccounts",
		},
		{
			freezeTableName: true,
		}
	);

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

		EmailAccount.belongsToMany(models.Project, { through: models.EmailAccountProject, foreignKey: "emailaccount_id", otherKey: "project_id", as: "projects" });

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

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

	return EmailAccount;
};
