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

module.exports = (sequelize) => {
	const DocType = sequelize.define(
		"doctype",
		{
			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 },
			display_name: { type: DataTypes.STRING(50), allowNull: false, unique: true },
			description: { type: DataTypes.TEXT, allowNull: true },
		},
		{
			tableName: "doctypes",
		},
		{
			freezeTableName: true,
		}
	);

	DocType.associate = (models) => {
		DocType.belongsToMany(models.Role, { through: models.Permission, foreignKey: "doctype_id", as: "roles" });
		DocType.hasMany(models.Permission, { foreignKey: "doctype_id", as: "permissions" });
		DocType.hasOne(models.WorkflowSetting, { foreignKey: "doctype_id", as: "workflowsetting" });
		DocType.hasMany(models.Workflow, { foreignKey: "doctype_id", as: "workflows" });
		DocType.hasMany(models.ImportLog, { foreignKey: "doctype_id", as: "importlogs" });
		DocType.hasMany(models.Comment, { foreignKey: "doctype_id", as: "comments" });
		DocType.belongsTo(models.User, { foreignKey: "modified_by", as: "modifier" });
	};

	return DocType;
};
