module.exports = (sequelize, DataTypes) => {
  const MaterialType = sequelize.define('MaterialType', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    type_code: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: 'Unique code for material type (e.g., RAW_MAT, SEMI_FIN, FIN_GOOD)'
    },
    type_name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: 'Name of material type (e.g., Raw Material, Semi-Finished Good)'
    },
    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_type',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'type_code']
      },
      {
        fields: ['company_id']
      },
      {
        fields: ['is_active']
      }
    ]
  });

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

  return MaterialType;
};

