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

module.exports = (sequelize) => {
  const ItemGroup = sequelize.define(
    "itemgroup",
    {
      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 },
      display_name: { type: DataTypes.STRING(150), allowNull: false },
      code: { type: DataTypes.STRING(20), allowNull: true },
      company_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: {
          model: "companies",
          key: "id",
        },
      },
    },
    {
      tableName: 'itemgroups',
    },
    {
      freezeTableName: true,
    }
  );

  /**
   * Associates the ItemGroup model with other models.
   * @param {object} models - The models to associate with.
   */
  ItemGroup.associate = (models) => {
    /**
     * A ItemGroup can have many companies associated with it.
     * Defines a one-to-many relationship between ItemGroup and Company.
     */
    ItemGroup.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });

    ItemGroup.belongsToMany(models.Territory, { through: models.TerritoryItemGroup, foreignKey: 'itemgroup_id', otherKey: 'territory_id', as: 'territories' });
    ItemGroup.hasMany(models.Item, { foreignKey: 'itemgroup_id', as: 'items' });
  };

  return ItemGroup;
};
