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

module.exports = (sequelize) => {
    const Video = sequelize.define('video', {
        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 },
        link: { type: DataTypes.STRING, allowNull: true },

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

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

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

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

    return Video;
};
