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

module.exports = (sequelize) => {
    const Image = sequelize.define('image', {
        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 },

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

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

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

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

    return Image;
};
