module.exports = (sequelize, DataTypes) => {
  const MaterialGroup = sequelize.define('MaterialGroup', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    group_code: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: 'Unique code for material group (e.g., CABINET, ASSEMBLY, PARTS)'
    },
    group_name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: 'Name of material group (e.g., Cabinet, Assembly, Parts)'
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    is_active: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    },
    updated_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    }
  }, {
    tableName: 'material_group',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'group_code']
      },
      {
        fields: ['company_id']
      },
      {
        fields: ['is_active']
      }
    ]
  });

  MaterialGroup.associate = function(models) {
    MaterialGroup.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    MaterialGroup.hasMany(models.Material, { foreignKey: 'material_group_id', as: 'materials' });
    MaterialGroup.belongsTo(models.User, { foreignKey: 'created_by', as: 'creator' });
    MaterialGroup.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updater' });
  };

  return MaterialGroup;
};

