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

module.exports = (sequelize) => {
    const SectionComponent = sequelize.define('sectioncomponent', {
        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, defaultValue: true },

        // main fields
        component_type: { 
            type: DataTypes.ENUM(
                'feature', 
                'card', 
                'image', 
                'video', 
                'quote', 
                'button'
            ), 
            allowNull: false 
        },
        title: { type: DataTypes.STRING(100), allowNull: true },
        content: { type: DataTypes.TEXT, allowNull: true },
        order: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
        
        // metadata for component-specific data
        metadata: {
            type: DataTypes.JSON,
            allowNull: true,
            defaultValue: {}
        },

        // foreign keys
        section_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
        },
        media_id: {
            type: DataTypes.INTEGER,
            allowNull: true,
        }
    }, {
        tableName: 'sectioncomponents',
        freezeTableName: true,
    });

    SectionComponent.associate = (models) => {
        // Belongs to Section
        SectionComponent.belongsTo(models.Section, { 
            foreignKey: "section_id", 
            as: "section" 
        });

        // Belongs to Media for images/videos
        SectionComponent.belongsTo(models.Media, { 
            foreignKey: "media_id", 
            as: "media" 
        });
    };

    return SectionComponent;
};