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

module.exports = (sequelize) => {
    const Document = sequelize.define(
        'document',
        {
            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(100), allowNull: false, unique: true },
            display_name: { type: DataTypes.STRING(150), allowNull: true, unique: true },
            description: { type: DataTypes.TEXT, allowNull: true },
            filename: { type: DataTypes.STRING, allowNull: true },

            // fk
            project_id: {
                type: DataTypes.INTEGER,
                references: {
                    model: 'projects',
                    key: 'id'
                }
            },
        }, {
        indexes: [{ fields: ['project_id'] }],
    }, {
        tableName: 'documents',
    }, {
        freezeTableName: true
    });

    /**
     * Associates the Document model with other models.
     * @param {object} models - The models to associate with.
     */
    Document.associate = (models) => {
        /**
         * Associates the Document model with the Project model.
         * Defines a many-to-one relationship between Document and Project.
         * @param {object} models - The models to associate with.
         */
        Document.belongsTo(models.Project, { foreignKey: 'project_id', as: 'project' });

        /**
         * Associates the Document model with the User model.
         * Defines a many-to-one relationship between Document and User.
         * @param {object} models - The models to associate with.
         */
        Document.belongsTo(models.User, { foreignKey: 'owner', as: 'user' });

        /**
         * Associates the Document model with the CourseDocument model.
         * Defines a many-to-many relationship between Document and CourseDocument.
         * @param {object} models - The models to associate with.
         */
        Document.belongsToMany(models.Course, { through: models.CourseDocument, foreignKey: 'document_id', otherKey: 'course_id', as: 'courses' });
    };

    return Document;
};
