module.exports = (sequelize, DataTypes) => {
  const MaterialReorderLevel = sequelize.define('MaterialReorderLevel', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    plant_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Plant',
        key: 'id'
      }
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Material',
        key: 'id'
      }
    },
    storage_location: {
      type: DataTypes.STRING(10),
      allowNull: true
    },
    reorder_level: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    minimum_stock: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    maximum_stock: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: true
    },
    reorder_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: true
    },
    lead_time_days: {
      type: DataTypes.INTEGER,
      allowNull: true,
      defaultValue: 0
    },
    last_reorder_date: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    is_active: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: 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_reorder_level',
    indexes: [
      { fields: ['company_id', 'plant_id', 'material_id', 'storage_location'], unique: true },
      { fields: ['is_active'] },
      { fields: ['status'] }
    ]
  });

  MaterialReorderLevel.associate = function(models) {
    MaterialReorderLevel.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    MaterialReorderLevel.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    MaterialReorderLevel.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    MaterialReorderLevel.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser' });
    MaterialReorderLevel.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updatedByUser' });
  };

  return MaterialReorderLevel;
};

