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

module.exports = (sequelize) => {
    const TerritoryVersions = sequelize.define('territoryversion', {
        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(100), allowNull: false },
        slug_name: { type: DataTypes.STRING(100), allowNull: true },
        valid_from: { type: DataTypes.DATEONLY, allowNull: false },
        valid_to: { type: DataTypes.DATEONLY, allowNull: false },

        // fk
        company_id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            references: {
                model: 'Companies',
                key: 'id'
            }
        },
    }, {
        tableName: 'territoryversions',
        freezeTableName: true
    });

    /**
     * Associates the TerritoryVersions model with other models.
     * @param {object} models - The models to associate with.
     * @description
     *   - A TerritoryVersion has many TerritoryVersionChilds.
     *   - A TerritoryVersion belongs to a Company.
     */
    TerritoryVersions.associate = (models) => {
        /**
         * Associates the TerritoryVersions model with the TerritoryVersionChild model.
         * A TerritoryVersion has many TerritoryVersionChilds.
         * @param {object} models - The models to associate with.
         */
        TerritoryVersions.hasMany(models.TerritoryVersionChild, { foreignKey: 'territoryversion_id', as: 'territoryversionchilds' });

        /**
         * Associates the TerritoryVersions model with the Company model.
         * A TerritoryVersion belongs to a Company.
         * @param {object} models - The models to associate with.
         */
        TerritoryVersions.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    }

    return TerritoryVersions;
};
