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

module.exports = (sequelize) => {
    const Question = sequelize.define(
        "question",
        {
            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 },

            number: { type: DataTypes.INTEGER, allowNull: true },
            title: { type: DataTypes.STRING, allowNull: true },
            text: { type: DataTypes.TEXT, allowNull: false },
            filename: { type: DataTypes.STRING, allowNull: true },

            // fk
            questionbank_id: { type: DataTypes.INTEGER, allowNull: false, },
        },
        {
            tableName: "questions",
            freezeTableName: true,
        }
    );

    /**
     * Associates the Question model with other models.
     * @param {object} models - The models to associate with.
     */
    Question.associate = (models) => {
        /**
         * Associates the Question model with the QuestionBank model.
         * Defines a many-to-one relationship between Question and QuestionBank.
         * @param {object} models - The models to associate with.
         */
        Question.belongsTo(models.QuestionBank, { foreignKey: "questionbank_id", as: "questionbank" });

        /**
         * A Question has many Answers.
         * Defines a one-to-many relationship between Question and Answer.
         * @param {object} models - The models to associate with.
         */
        Question.hasMany(models.Answer, { foreignKey: "question_id", as: "answers" });

        /**
         * A Question has many UserAnswers.
         * Defines a one-to-many relationship between Question and UserAnswer.
         * @param {object} models - The models to associate with.
         */
        Question.hasMany(models.UserAnswer, { foreignKey: "question_id", as: "useranswers" });
    };

    return Question;
};
