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

module.exports = (sequelize) => {
    const Workflow = sequelize.define(
        "workflow",
        {
            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: true },
            owner: { type: DataTypes.INTEGER, allowNull: true },

            status: { type: DataTypes.STRING, allowNull: false },

            // fk
            doctype_id: { type: DataTypes.INTEGER, allowNull: false },
            doc_id: { type: DataTypes.INTEGER, allowNull: false },
        },
        {
            tableName: "workflows",
            freezeTableName: true,
        }
    );

    Workflow.associate = (models) => {
        /**
         * A Workflow has many WorkflowApprover.
         * @param {object} models - The models to associate with.
         * @description
         *   - A Workflow can have many WorkflowApprovers.
         *   - A WorkflowApprover belongs to one Workflow.
         */
        Workflow.hasMany(models.WorkflowApprover, { foreignKey: 'workflow_id', as: 'workflowapprovers' });

        /**
         * A Workflow belongs to one Doctype.
         * @param {object} models - The models to associate with.
         * @description
         *   - A Workflow belongs to one Doctype.
         *   - A Doctype has many Workflows.
         */
        Workflow.belongsTo(models.DocType, { foreignKey: 'doctype_id', as: 'doctype' });
    };

    return Workflow;
};
