module.exports = (sequelize, DataTypes) => {
  const InventoryStockAdjustmentItem = sequelize.define('InventoryStockAdjustmentItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    adjustment_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'InventoryStockAdjustment',
        key: 'id'
      }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Material',
        key: 'id'
      }
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    system_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0,
      comment: 'System stock quantity before adjustment'
    },
    physical_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      comment: 'Physically counted quantity'
    },
    adjustment_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      comment: 'Difference (physical - system)'
    },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'UOM',
        key: 'id'
      }
    },
    unit_price: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0
    },
    adjustment_amount: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0,
      comment: 'Value adjustment (adjustment_quantity * unit_price)'
    },
    batch_number: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'inventory_stock_adjustment_item',
    indexes: [
      {
        fields: ['adjustment_id']
      },
      {
        fields: ['material_id']
      }
    ]
  });

  InventoryStockAdjustmentItem.associate = function(models) {
    InventoryStockAdjustmentItem.belongsTo(models.InventoryStockAdjustment, { foreignKey: 'adjustment_id', as: 'adjustment' });
    InventoryStockAdjustmentItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    InventoryStockAdjustmentItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
  };

  return InventoryStockAdjustmentItem;
};

